Results 1 to 2 of 2
Thread: constructor calling sequence.
- 02-04-2010, 02:24 PM #1
constructor calling sequence.
Hi.
I have a doubt in following code.
class Super
{
Super(int x)
{
System.out.println(x);
}
}
class Sub extends Super
{
Sub(int k)
{
super(k);
System.out.println("Inside sub class");
}
}
class Main
{
public static void main(String []args)
{
Sub obj = new Sub(5);
}
}
We have been told that before sub class constructor super class constructor runs.And if that does happen how come sub class constructor is supplying parameter to super class constructor.Also if we skip the whole constructor of sub class then compiler flashes error.
Please help.
THanks.
- 02-04-2010, 02:40 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,484
- Rep Power
- 16
The super class constructor is called on the line super(k). If you don't have this line then it will call the default (no parameters) constructor of the parent. If the parent does not have a no parameters constructor then you'll get a compiler error.
So, the constructor for Sub is called, which then calls the constructor for its parent (Super), before returning to the Sub constructor.
There are some more steps to this, but that should do you for now.
Similar Threads
-
Calling a constructor from another one.
By Somelauw in forum New To JavaReplies: 1Last Post: 11-28-2009, 03:42 PM -
calling sequence
By rocky in forum Web FrameworksReplies: 0Last Post: 04-27-2009, 08:35 PM -
Constructor calling
By ravian in forum New To JavaReplies: 2Last Post: 12-22-2007, 06:53 PM -
Calling constructor of parent class from a constructor
By Java Tip in forum Java TipReplies: 0Last Post: 12-19-2007, 09:10 AM -
Calling constructor of same class from a constructor
By Java Tip in forum Java TipReplies: 0Last Post: 12-19-2007, 09:01 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks