A subclass is dependant on its superclass, and this dependancy is unidirectional. A superclass cannot have a dependancy on a subclass.How can a developer design a superclass that knows about ALL of its subclasses? Deriving from a class provides you with the same functionality as the superclass. How does the superclass know about the subclass, since it is added at a later date (due to the unidirectional dependancy)? Perhaps what it is in the subclass actually belongs in the superclass? Perhaps you need to use the Template Method Design Pattern? This is clearly speculation and a more concrete solution can only be arrived at with some more thought on your specific problem.
Consider this code
In the Test class we are creating an object of the Derived class.The Derived class constructor is called.This in turn calls Base class constructor.method addValue() is overriden in the Base class.When this method is called from the Base class I think addValue() from the Base class should be the one which should be called since Base class knows only about its methods and variables and nothing about methods or variables in the derived class.Why is the method addValue() form the Derived class called?Does it not contradict concept of inheritance.What I believe is that subclass is more specialized and superclass knows nothing about the specific behavoir of its subclass.please explain.
This a great example and I learned something from it. What's happening here is , as per the Template Method Pattern, the Base.class (superclass) is letting the Derived.class (subclass) redefine the certain steps in the algorithm. In other words, the Derived.class (subclass) is providing the implementation of the addValue() method.
If you remove the addValue() method from the Derived.class the superclass will use its own implementation of addValue() as expected.
The superclass does not need to know about the subclass, the dependency, like you said, is unidirectional. Its like parent teaching the kid how to do somthing, and kid mostly follows all the steps later, but few of the steps the kid does its own way. Only at runtime, the superclass lets the subclass follow steps "in its own way." Not the best analogy, but it helps me.