• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriden methods and contructor chaining

 
Tanveer Mehmood
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see the code below. I'm confused about the overridden method calls which occur during constructor chaining from derived to base....
class sup
{
int val;
public sup()
{
System.out.println("Executing super");
this.func(); // (2)
System.out.println("Exiting super");
}
protected void func()
{
val = 10;
System.out.println(val);
}
}
public class sub extends sup
{
public static void main(String args[])
{
sub i = new sub(); // (1)
}
protected void func() // (3)
{
}
}

Output of above code is:
"Entering super"
"Exiting super"
My question is that when base class constructor is called through derived class' constructor, why the version of func in derived class is called and not in base, while base class constructor explicitly calls its own version of function through this. Hope you guys understand my question.
 
lee dalais
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Tanveer
when u specify "this" it refers to the current object and u have overriden the method func() in the subclass, so since u created an instance of the sub it refers to instance 'i', so in other words i.func();.
anyone pls correct where i'm wrong.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is what overriding is all about. Since the type of the object is a sub, the "this" will have sub's behaviors (methods), which includes all the methods in sub, and the methods that it inherits but doesn't override from sup.
If you WANT to execute the method from sup you need to explicitely make a call to super.func(). Of course you could not put that in the super class itself because if you ever make an instance of sup then when you call super.func() it would not be able to find that method in sup's only super, which is object.
 
Tanveer Mehmood
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Cindy,
You made it really clear...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic