This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

about this?  RSS feed

 
You Lu
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A
{
String data = "A";
public A()
{
System.out.println(this.data);
this.draw();
}
public void draw()
{
System.out.println("A.draw():" + data);
}
}
public class B extends A
{
String data = "B";
public B()
{
super();
}
public void draw()
{
System.out.println("B.draw(): " + data);
}
public static void main(String[] args)
{
B b = new B();
}
}

Execution Result:

A // "this.data","this" is point to A.??
B.draw(): null //"this.draw()","this" is point to B.

What I dont understand is when the code executed until super(), it will call A.A(), but inside A constructor, "this" is point to B, but "this.data" is refer to A.

Can anybody understand the processing of this code and tell me the procedure of execution.Thanks
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Perhaps this will help:
http://www.xdweb.net/~dibblego/java/trivia/

Note that calling an overridable method (one that is non-private, non-static, non-final, a member of a non-final class, and a member of a class with at least one non-private constructor) on an implicit or explicit 'this' reference is extremely poor form, for the reasons that you are observing and a few more.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, I have put back the formatting of your program and surrounded it with code tags
[ CODE ] your program [/ CODE ] omit the spaces inside the []


Isn't that easier to read?

To answer your question, variable references are bound at compile time and unqualified variable references use the version of the variable declared in or inherited by the class containing the code being executed. If there is no qualifier, this is implied. Putting it in changes nothing. Exception - if there is a formal parameter or local variable with the same name, this specifies the instance variable while leaving it off specifies the local variable or formal parameter.

Instance methods are bound at execution time and are selected based on the actual type of the object. The facts that the method was called from a constructor and that the method was called on this changes nothing.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!