aspose file tools*
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriden methods and contructor chaining" Watch "Overriden methods and contructor chaining" New topic
Author

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;
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

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"
Sheriff

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: http://aspose.com/file-tools
 
subject: Overriden methods and contructor chaining
 
Similar Threads
method overriding doubt
Doubt in Constructors
probleme in constructor(Help)
A simple Q but still have doubt
constructor giving headache