This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How is this??" Watch "How is this??" New topic

How is this??

Ramesh Tiwari

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?

class Base
int i = 99;
public void amethod()
public class Derived extends Base
int i = -1;
public static void main(String argv[])
Base b = new Derived();
public void 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 ]
It is sorta covered in the JavaRanch Style Guide.
subject: How is this??
Similar Threads
Method from constructor
Please explain this question from mock exam.
Mock Exam question.
inheritance question
Doubt in Mock Question