+ 4

Why is it like this in polymorphism?

The super class reference variable can be used to access the sub class methods only if that method is overrided orelse raises error.

6th Mar 2017, 5:20 PM
Gautham Raj S
Gautham Raj S - avatar
6 odpowiedzi
+ 10
Why should the super class call a method from the sub class if it doesn't override the method? Why do you need inheritance, if you just want to call a method from a class explicitly? Could you help us by describing your problem in detail? Maybe inheritance isn't the best solution for your problem?
6th Mar 2017, 5:31 PM
Tashi N
Tashi N - avatar
+ 9
Then you could pass the base class object to the super class as a parameter to the constructor of the super class. But I doubt that this is good design.
6th Mar 2017, 7:42 PM
Tashi N
Tashi N - avatar
+ 8
Search for 'visitor pattern'. That uses interface instead of inheritance but I think it is what you are asking for.
6th Mar 2017, 6:19 PM
Tashi N
Tashi N - avatar
+ 3
If we could access other methods of the sub class through the reference variable of the super class it would be more flexible.
6th Mar 2017, 5:36 PM
Gautham Raj S
Gautham Raj S - avatar
+ 3
The superclass doesn't know about the subclasses. Let's say programmer 1 writes animal class and programmer 2 writes dog and extends animal, the first programmer doesn't know what methods are in the subclass he/she doesn't even know if other classes extend animal or not, even if he knows what good comes out of that?! what if you access a dog method in animal and then cat extends animal?! what happens if you pass a cat object to that method?!!
6th Mar 2017, 9:22 PM
Mohamad Sharifi
Mohamad Sharifi - avatar
+ 1
Let Animal be the super class and dog,cat be subclasses. By the Animal reference variable we can acces the overridden methods of the subclasses ,but I want to access the non-overridden methods of dog,cat classes(sub classes) with the same super class ref. variable is it possible..
6th Mar 2017, 6:27 PM
Gautham Raj S
Gautham Raj S - avatar