Monday, June 18, 2012

Super Keyword


Super Keyword

Using super Keyword

The base class constructor can be called in a derived class or subclass using super() in the constructor.

Example :
class A
{
int a;
A()
{
System.out.println ("This is A default constructor");
}
A (int a)
{
this. a=a;
System.out.println ("This is A one arg constructor"+a);
}
}
class B
{
B()
{
super();
System.out.println ("This is B default constructor");
}
B (int a,int b)
{
super (a);
this.b=a;
System.out.println ("This is B one arg constructor"+b);
}
}
class ConstructorOverloading
{
public static void main (String as[])
{
B b1= new B ();
B b2= new B(99,88);
}
}
Output:
This is A default constructor.
This is A one arg constructor 99
This is B default constructor
This is B one arg constructor 88.

» When you have super class and subclass, with subclass object we can call both
subclass members and super class members.
» Super class object is not required, but when you create super class object then
only superclass constructor will be invoke.
» Using super keyword ,we can invoke the super class constructor without creating
superclass object.

» We can write super with different signatures like :
» super(a);
» super(a,b);
» super(a,b,c..);

» When you are not writing any super() JVM insert default super().
» When you are writing super(), JVM won't insert default super().
» Super() must be the first line in the constructor.
» More than one super() is not allowed inside a constructor.
» Both this() and super() are not allowed inside a constructor at a time.
» Constructor invoking order is from bottom to top (subclass to super class).
» Constructor execution order is from top to bottom (super class to subclass).

No comments:

Post a Comment