Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Super() - Keyword in JAVA

Status
Not open for further replies.

munnanext

Programmer
Aug 20, 2004
49
US
I have a ClassA and ClassB. ClassB is inherited from ClassA. When I create an Object of ClassB it is Calling ClassB constructer, which is Fine. But Once the control goes to ClassB Constructer it is calling ClassA Constructer even if I don't call Explicitly by using Super() Keyword.

I learned that we need to use "Super()" keyword in the SubClass when we want to call Super Class Constructor.
But even with out calling Explicitely Super Class Constructer is being called.

Eg:
//Class A
Class ClassA {

public ClassA(){
//Constructor
//-> This is being called by ClassB Constructor with
out using Super Key Word.
}
}
//Class B
Class ClassB extends ClassB{

public ClassB(){
//Constructor
//-> Once the control comes here it is calling Super
Class Constructor.

}
public static void main(String[] args){
ClassB objClasB = new ClassB();
// -> Once this is done the control goes to Constructor
of this Class.

}
}

Can you pl explain . Thanks
 
Yes.
The super-constructor must be called.
I'm no native english speaker, but your explanation doesn't seem accurate to me (and your example is worse: Class ClassB extends ClassB {) (recursion: see recursion).

Class B extends A.
So B is inheriting A, and A is inherited by B - if my english isn't too bad.

But to the content.
B is a A. Or a kind of A.
The A-part needs to be constructed, so the constructor must be called.
This will be done automatically, if A has an parameterless constructor, implicitly.
If A has no parameterless ctor, you have to choose it explicitly (and pass the parameter(s)).

seeking a job as java-programmer in Berlin:
 
Thanks for the Clarification
I am soory about my Typo.

The below is the stmt I wanted to write.
Class ClassA extends ClassB {)
 
The super()-method is mostly used if you want to call a parameterized version of the constructor of a parent class.
e.g.:
Class A{
public A(int iAValue){
....
}
}

Class B extends A{
public B (int iBValue){
super (iBValue);
}
}
If you do not use the super()-method here, the standard constructor of class A is called.
 
Yeah, fair comment.
If you have parameterized variants of constructors of a parent class and you want to use the default constructor of this class, then you have to define this contructor explicitly.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top