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 Overriden methods and contructor chaining 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 "Overriden methods and contructor chaining" Watch "Overriden methods and contructor chaining" New topic

Overriden methods and contructor chaining

Tanveer Mehmood
Ranch Hand

Joined: Feb 23, 2001
Posts: 51
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;
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

Joined: Feb 28, 2001
Posts: 67
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"

Joined: Sep 29, 2000
Posts: 8521
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.

"JavaRanch, where the deer and the Certified play" - David O'Meara
Tanveer Mehmood
Ranch Hand

Joined: Feb 23, 2001
Posts: 51
Thanks Cindy,
You made it really clear...
I agree. Here's the link:
subject: Overriden methods and contructor chaining
Similar Threads
constructor giving headache
A simple Q but still have doubt
Doubt in Constructors
probleme in constructor(Help)
method overriding doubt