Pages

CONSTRCUTORS Programmes

/** Program to call a constructor of a class from another constructor */
class ThisDemo3
{
 int a,b;
 ThisDemo3()
 {
 System.out.println("Inside constructor without parameters");
 a=10;
 b=20;
 }
 ThisDemo3(int x)
 {
 a=x;
 b=x;
 System.out.println("Inside constructor with one parameters");
 }
 ThisDemo3(int x,int y)
 {
  this(x);// x value passed to ThisDemo(int x)
 System.out.println("Inside constructor with two parameters");
 }
 public static void main(String args[])
 {
 ThisDemo3 t1=new ThisDemo3();
 System.out.println("t1.a = " + t1.a);
 System.out.println("t1.b = " + t1.b);
 ThisDemo3 t2=new ThisDemo3(10,20);
 System.out.println("t2.a = " + t2.a);
 System.out.println("t2.b = " + t2.b);
 }
}
NOTE: 1. 'this' keyword must be used only in either constructors or non-static methods of a class. It cannot be used in static methods of a class.
2. Writing two or more this call in the same constructor is wrong.
Example:
class Sample{
Sample(){
…..
……
}
Sample(int a){
this();
this();
…..
…..
}
}// it is wrong
3. Writing the this call as second statement is also wrong
Example:
class  Ramesh{
Ramesh(){
System.out.println(“I am in cons”);
this(30);
}
System.out.println(“some mess”);
}// it is wrong
4. Recursive methods calls are allowed in java but recursive constructor calls are not allowed in java.
Static and non-static blocks:
These are a set of statements that can be defined with the keyword static or without static. Any block that starts with static keyword is called a static block.Its syntax is:
static
{
---
}
->Any block defined without a name or static keyword is called a non-static block. Its syntax is :
{
----
}