MY mENU


Thursday 9 February 2012

Super() Example



Super() Example:  In Java Programming The first statement of a constructer is Super();if u don't call forcefully(explicitly).


Ex:
Public class ConstructerClass{
ConstructerClass(){
super();
}
}

In the above class when you don't write The super() in the constructerClass() then at the time of compilation a default super() call will be add by the compiler.Which is nothing but the constructer of Object class.
 .
Ex2:
public class A{
A()  //constructer defined by user
{
}
}
public class B extends A{
B(int x){
//here the first call is to super class default constructer i.e super()
}
}
when you create "new B(5)" then it will compile and run fine because there is a default constructer (written by us )is present .
Ex3:

public class A{
//no constructer defined by us
}
public class B extends A{
B(int x){
//here the first call is to super class default constructer i.e super()
}
}
by creating "new B(5)"
this also compiles fine because implicitly there is a default constructer
Ex4:

public class A{
A(String s){
}
}
public class B extends A{
B(int x){
//here the first call is to super class default constructer i.e super()
}
}
in this case by creating "new B(5)" we will get compilation error because there is no implicit or explicit default constructor called by B's constructer .
So to compile and run successfully u have to write a default constructer in class A. As


EX.5
public class A{
A(){
}

A(String s){
}
}
public class B extends A{
B(int x){
//here the first call is to super class default constructer i.e super()
}
}
Important note:
A compiler write a default constructer for you if you dont write any constructer ; if u write an arguemented constructer then compile will not write a constructer for you . so be care full.

No comments:

Post a Comment