1 Aug 2012

super() in java with example


A class can contain a single default constructor and 'n' number of constructors. If you want to call 
the base class constructors from the derived class constructors, in java we have two methods.
1.super()
2.super(...)

this(): It is used for calling super class's default constructor from the default(zero argument) or parameterized constructor of derived class and applying super() in the context of derived class constructors is optional.
this(...): It is used for calling  super class's  parameterized constructor from the default(zero argument) or parameterized constructor of derived class.
     Whenever we use either super() or super(...) in the current class constructors, they must be used as first statement in the current class constructors. Otherwise, we get compile-time error.

Sample Code:

class test
{
  int a,b;
  test()
   {
     test(1000);
     a=10;
     b=20;
     System.out.println("a: "+a);
     System.out.println("b: "+b);
    }
    test(int x)
    {
      a=b=x;
      System.out.println("a: "+a);
      System.out.println("b: "+b);
    }
}

class test1 extends test
{
 test1()
{
 super();
 }
}
class demo
{
 public static void main(String arg[])
 {
   test1() t=new test1();
 }
}

0 comments:

Post a Comment