• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Reference Variable and Object Types

 
Alan Blass
Ranch Hand
Posts: 161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi! I have compiled this:



If anyone found any mistakes, please correct me. Thanks.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 SuperClass
  • invoke only methods from SuperClass
  • when 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 SuperClass
  • invoke only methods from SuperClass
  • when 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 SubClass
  • invoke methods from SuperClass and SubClass
  • when 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
     
    Alan Blass
    Ranch Hand
    Posts: 161
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks a lot, Roel.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic