• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about this?

 
You Lu
Greenhorn
Posts: 7
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic