1 Aug 2012

this() in java

A class can contain a single default constructor and 'n' number of constructors. If you want to call 
a constructor of same class from another category constructor of same class then you must use the following methods.
1.this()
2.this(...)

this(): It is used for calling a default constructor from parameterized constructor of same class.
this(...): It is used for calling a  parameterized constructor of current class from another category constructors of same class.
     Whenever we use either this() or this(...) 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 demo
{
 public static void main(String arg[])
 {
   test() t=new test();
 }
}

0 comments:

Post a Comment