I was wondering, is it possible that a superclass to access the methods of a inherited subclass, like for example in Java?
I know that a subclass can override and even implements, in case of abstract classes, the methods of the superclass, but the question mentioned above is possible?
Thanks
Example in c#.. in superclass make abstract method, which is implemented in derived class
Java, PHP, Ruby, Python, C# (and so on) methods are always virtual, so, no matter what, when you override a method in a subclass, this version will be called:
So, you not just CAN access your subclass method, you HAVE TO.
Just for comparison, in C++, for example, things work different. If you don't declare a method as virtual, you can't override it.
I' ll try to explain as they explained to me at university.
You have a reference:
His static type(ST) is Object : this is his own type and never changes.
His dynamic type(DT) is also Object(in this case): the reference point to an object of type Object, but it can change.
for example if i write :
That being said:
Upcasting is always permitted: consider two references s and r. the assignment s=r compile and execute always if
ST(r) <= ST(s)
(the static type of r is, in the hierarchi, less or equals to the static type of s)for example:
Downcasting: at compile-time it is always legal to downcast from a type X to a type Y if X and Y belong to hierarchy. Consider the reference s. I want to cast s to a type C, so if C <= TS(s) it will always compile if I do the cast as :
C r = (C)s
for example:
When we run our application if the downcast fails, Java raise an Exception. Otherwise it success.
To downcast correctly: consider a reference ref and we want to cast to a type C. So a downcast will success if
DT(ref) <= C <= ST(ref)
.And the downcast will be obtained as:
C ref2 = (C)ref
for example:
PS: please forgive if I made some mistake but I wrote a bit in a hurry.
In Java, It's not possible, and I think what you are asking would go against OOP.