classGraduateStudentextendsStudent{ //nothing here /* GraduateStudent does not have a toString method Therefore when calling m(new GraduateStudent()), It gets the superclass's method in runtime. */ }
classStudentextendsPerson{ public String toString(){ return"Student"; } }
classPersonextendsObject{ public String toString(){ return"Person"; } }
Output
1 2 3 4
Student Student Person java.lang.Object@293e75df
Which implementation is used will be determined dynamically by the Java Virtual Machine (JVM) at runtime.
This capability is known as dynamic binding.
Another example of Runtime polymorphism (dynamic binding)
publicclassTest{ publicstaticvoidmain(String args[]){ A a = new B(); //Type is A but point to B a.p(); //Invoke void p() of B (overrided) B b = new B(); //Type is B, point to B b.p(); //Invoke void p() of B } }
//Output: BB
Note if the Methods are static, they will not get overrided.
publicclassTest{ publicstaticvoidmain(String args[]){ A a = new B(); //Type is A but point to B a.p(); //Invoke void p() of A because Static B b = new B(); //Type is B, point to B b.p(); //Invoke Static void p() of B } }
//Output: AB
Recall: when calling static method, we can call the method without new an object.
classA{ int i = 10; } classBextendsA{ int i = 20; } classCextendsB{ int i = 30; }
publicclassTest{ publicstaticvoidmain(String args[]){ A a = new C(); System.out.print(a.i + " "); C c = new C(); System.out.print(c.i + " "); B b = new B(); System.out.print(b.i); } }
classTest{ publicstaticvoidmain(String[] args){ //Person aa = new Person(); //Teacher aa = new Person(); //error: incompatible types: Person cannot be converted to Teacher Person aa = new Teacher(); //Teacher aa = new Teacher(); aa.p(44); } }
publicclassTest{ publicstaticvoidmain(String args[]){ A aa = new A(); B bb = new B(); aa.p(123.2); bb.p(456.7); aa = new B(); bb = new B(); aa.p("Cat1"); //Error incompatible types: String cannot be converted to double aa.p(44); // A 44.0 bb.p("Cat2"); // Cat2 bb.p(55); // B 55 }
}
Inheritance vs Polymorphism
Inheritance is implemented on the classes
Polymorphism is implemented on methods/functions.
Accessibility Summary
Modifier on members in a class
Accessed from the same class
Accessed from the same package
Accessed from a subclass
Accessed from a different package
public
Yes
Yes
Yes
Yes
protected
Yes
Yes
Yes
No
default
Yes
Yes
No
No
private
Yes
No
No
No
A Subclass Cannot Weaken the Accessibility
A subclass may override a protected method in its superclass and change its visibility to public.
However, a subclass cannot weaken the accessibility of a method defined in the superclass.
For example, if a method is defined as public in the superclass, it must be defined as public in the subclass.
final Class Modifier
The final class cannot be extended
The final method cannot be overridden by its subclasses