aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes about this? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "about this?" Watch "about this?" New topic
Author

about this?

You Lu
Greenhorn

Joined: Jan 19, 2005
Posts: 7
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

Joined: Sep 24, 2003
Posts: 1608


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.


Tony Morris
Java Q&A (FAQ, Trivia)
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
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.


Mike Gershman
SCJP 1.4, SCWCD in process
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: about this?