• Post Reply Bookmark Topic Watch Topic
  • New Topic

"this" uses subclass method but not subclass instance-variable  RSS feed

 
Sven Sylta
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to figure out the output in this code. The first output should be "2" because the a-reference in Main finds the doIt-method in class B with dynamic binding.
The second and third output confuses me. Why does "this" in the doOther-method first use a member of A(instance-variable) and then use a member of B(doIt-method)?
What's happening here? Thanks.

Output is: "2" , "1" , "2"

 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the scope of the doOther method in class A, how do you expect it to know that a child class has an instance variable named i? A parent class knows nothing about the logic of its child classes.
 
Sven Sylta
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James Boswell wrote:In the scope of the doOther method in class A, how do you expect it to know that a child class has an instance variable named i? A parent class knows nothing about the logic of its child classes.


That makes sense. But shouldn't the output be 2,1,1 then?
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, because invoking a method is different.

In this case, the type of the object will determine which method is called. Class B overrides the doIt() method and as it is the object type, its version of the method is invoked.
 
Jayesh A Lalwani
Rancher
Posts: 2762
32
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) You cannot override data members in Java. You can only override methods. So, if you have declared a data member called i in base class, and a member called i in derived class, practically, you have 2 members named i. However, if you have a overriden method, then you have only one method. Pratictically, the method declared in base class "dissapears"
2) this in a base class uses the class definition of the base class. So, this.i in the base class will refer to the variable i that is defined in base class. this.i in the derived class refers to the variable i defined in derived class
3) However, since methods are overriden, the above rule doesn;t apply to overriden methods. this.doIt will always refer to the implementation of doIt in the derived class, no matter where it;s called from
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!