Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How is this??

 
Ramesh Tiwari
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic