Abstract Class Design

T

thomson

Hi
Some design queries on Abstract Class

abstract Class thomson
{
abstract void MyMethod();

virtual void NewMethod()
{

}

}


When in the base class i extend the above Abstract class , you have to
implement the MyMethod , and may be you can override the NewMethod if
necessary,

But Both looks the same thing , the class which extends can make use of
the two methods,


Why this, Can anyone letme know, why both these things


Thanks in Advance

thomson
 
N

Nick Hounsome

thomson said:
Hi
Some design queries on Abstract Class

abstract Class thomson
{
abstract void MyMethod();

virtual void NewMethod()
{

}

}


When in the base class i extend the above Abstract class , you have to
implement the MyMethod , and may be you can override the NewMethod if
necessary,

But Both looks the same thing , the class which extends can make use of
the two methods,


Why this, Can anyone letme know, why both these things

It's the difference between "CAN override virtual method" and "MUST
implement abstract method".

If there is a sensible default implementation then it is common to go for
virtual methods otherwise you need abstract methods.
 
G

Greg Young

public class Dog {
public virtual void Speak() {
Console.WriteLine("Woof");
}
}

most our dogs just go woof ...

public class Rottweiler : Dog {}
public class Mastiff : Dog {}
public class Shitzu : Dog {}

some need to do something completely different than the default
public class DogThatThinksItIsACat : Dog {
public override void Speak() {
Console.WriteLine("Meow");
}
}

some need to extend the default
public class TalkativeDog : Dog {
public override void Speak() {
Console.WriteLine("WoofWoofWoof");
base.Speak();
}
}

In this case 99% of the dogs will go "woof" so implementing the same method
in every one of their derived classes would not make alot of sense ...
however when we get to one that needs to change or extend the default
behavior we can override the default and provide our own.

Cheers,

Greg Young
MVP - C#
 
J

Joanna Carter [TeamB]

"Greg Young" <[email protected]> a écrit dans le message de e%[email protected]...

| public class Dog {
| public virtual void Speak() {
| Console.WriteLine("Woof");
| }
| }
|
| most our dogs just go woof ...

That may explain virtual methods, but abstract methods are akin to declaring
:

public class Animal
{
public abstract void Speak();
}

All animals speak, abstract says we don't know how at this level of
inheritance.

public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof");
}
}

Then, because override also implies virtual, we can then go on to declare
subclasses of Dog that may speak in a non-default manner as in Greg's
example.

Joanna
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top