Alan Blass wrote:If anyone found any mistakes, please correct me. Thanks.
After searching for 9 days
I spotted one mistake, not in the code but in your comments. And maybe some of your comments could also be rephrased a little bit better.
Let's start with the mistake!
System.out.println(b.returnA()); //results: Calling the method in SubClass. Prints "SubClass"
You call/invoke the method in
SuperClass, but because the method
returnA is overridden in
SubClass, the method in
SubClass is executed. That's (as you probably already know)
polymorphism! But you do
not call the method in
SubClass. This results in a very easy, but very very very important rule:
which methods you can call/invoke is determined by the type of the reference variable, which method is executed depends on the type of the actual object (the reference variable is referring to). Regarding fields, there's one even simpler rule:
the type of the reference variable determines which fields you can access.
With these rules in mind, you could rephrase your first 4 comments to make it (hopefully) more clear:
SuperClass a = new SuperClass(); //all methods in SuperClass. None in SubClass. Properties in SuperClass called.
access fields from SuperClassinvoke only methods from SuperClasswhen you invoke a method, the method defined in SuperClass will always be executed (no polymorphism)
SuperClass b = new SubClass(); //all methods in SuperClass. Only overridden methods in SubClass. Properties in SuperClass called.
access fields from SuperClassinvoke only methods from SuperClasswhen you invoke a method and the method is overridden in SubClass, the method in SubClass is executed; otherwise the method in SuperClass will be executed (polymorphism)
SubClass c = new SubClass(); //all methods in SuperClass. All overridden methods in SubClass. All subClass methods. Properties in SubClass called.
access fields from SubClassinvoke methods from SuperClass and SubClasswhen you invoke a method and the method is defined in SubClass, the method in SubClass is executed; otherwise the (inherited) method from SuperClass will be executed (no polymorphism)
Hope it helps!
Kind regards,
Roel