C# Inheritance Problem
Let's say I have 3 classes:
GrandDad, Dad and Son. Son inherits from Dad, which inheri开发者_Go百科ts from GrandDad.
GrandDad has 2 methods:
public virtual void foo();
public virtual void do();
Dad inherits foo(), but overrides do();
public override void do();
If Son wants to modify foo(), is it acceptable to:
make Dad override foo(), but simply call foo.base()? Then Son can override foo(), but Dad's foo() functionality remains the same?
Or is that a hacky way?
As long as Dad
never defined a foo()
, there's no reason he has to do anything. Son
should be able to override foo()
from GrandDad
.
If I've understood your question, there's no need to do anything with Dad. Simply implement foo() within Son.
As Son is a descendant from Dad, nothing within Son changes Dad, so if Son implements foo(), Dad's foo() remains the same, inheriting from GrandDad.
Dad
doesn't have to override foo()
. Since Dad
simply inherits the version supplied by Granddad
(which is still virtual
), that means that's what Son
gets, too, allowing Son
to override foo()
.
public class Granddad {
public virtual void foo() {...}
public virtual void do() {...}
}
public class Dad {
public override void do() {...}
}
public class Son {
public override void foo() {...}
}
The semantics of the problem may have lead you astray.
If you are REALLY doing Father, Son, Grandfather...
You only need one class: Person. It will have a member property called Father that will point to another Person. This way, you can have many generations instead of being locked in at three.
What do you mean by modify foo
? If you mean override, then Son can simply override foo()
. No need to make Dad override foo()
calling base implementation.
Dad doesn't need to override Foo for Son to override Foo. Foo is virtual all the way up the inheritance chain unless someone overrides it AND declares it sealed.
精彩评论