Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How is this?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How is this??" Watch "How is this??" New topic
Author

How is this??

Ramesh Tiwari
Greenhorn

Joined: Jul 03, 2003
Posts: 9
The following code prints "Derived.amethod() 99 Derived.amethod()".
How did amethod() of Derived class get called from Base class constructor?
Thanks

class Base
{
int i = 99;
public void amethod()
{
System.out.println("Base.amethod()");
}
Base()
{
amethod();
}
}
public class Derived extends Base
{
int i = -1;
public static void main(String argv[])
{
Base b = new Derived();
System.out.println(b.i);
b.amethod();
}
public void amethod()
{
System.out.println("Derived.amethod()");
}
}
Tony Collins
Ranch Hand

Joined: Jul 03, 2003
Posts: 435
When accessing a method from a reference( in this case the reference is this)
the overiding method always gets called.
When calling amethod() from the base constructor you are implicitlly calling it from the this reference. So the amethod() in derived will be called.
Incidentally when you access a field via a reference you access the field associated with the class that the reference is of.So the other way around for fields.
Brian Joseph
Ranch Hand

Joined: May 16, 2003
Posts: 160
The key thing is that when instantiating the Derived object, the "this" reference that is used in the Base constructor is of the type Derived. You can prove this by doing 'this instanceof Derived' from within the Base constructor. However, member variables and static methods are resolved by the class type of the enclosing class, which is Base.
[ July 03, 2003: Message edited by: Brian Joseph ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How is this??