Friday, March 26, 2010

7 - method : overriding and polymorphism

a)  . operator can be used on any member at any place if it is accessible at that place (based on access modifier properties)

b)  If at any place a  . operator can be used on any super class method (how ever high it is in hierarchy) then only it can be overridden at that place

c) If you use super class reference polymorphically and call a method, then if the actual object (sub class) has overridden that method then actual object's method gets called at run time and if it has not overridden then the super class reference type's method is called at run time

d) subclass will have inherited method from super class as if it has defined it. But while checking for overriding of an inherited method check as if in the class where it has been defined it overrides or not, if it overrides then then subclass where it has been inherited is also a overridden method.

e) Ex. two cases - shown in diagram












in  the first case the public method1()* is not an override of method1() as method1() cannot be accessed using . operator in class2
in the second case the public method1()* is an override of method1() as method1() can be accessed using . operator in class3

f) so if use the reference type of class1 polymorphically but actual object is class2 then if you call method1() on the reference then method1() of class1 only gets called but if the actual object is class3 then public method1() *  of class3 gets called

g) If you're using a superclass type object reference polymorphically (the actual object is actually a subclass of the reference type) -
at compile time -it is only checked if the super class has that method (abstract also ok)
at run time if the subclass has the overridden method then it is called else the super class reference type's method gets called.
at run time even if the sub class has the overridden method but is not accessible  then super class reference type's method gets called

No comments:

Post a Comment