Introduction to Java

Java Programming is concisely explained.

6. Constructor

Constructor is a special method which is more like an instance method than a class method, for it is related with instance. Constructor can access all of instance fields and methods and static fields and methods. However, it can run without instance, a feature of static method. Constructor’s major features are:
1)Its name is always same as the class name.
2)It is used to create an instance of the class.
3)It has no return value.
4)If a constructor is executed in a constructor, it must be done at the top. This is done by this(), or this(,,,), whatever is defined. Even if a constructor is executed in a constructed, no new instance is created in a instance.
5)One no-parameter constructor is automatically and implicitly defined if no constructor is explicitly defined.
6)A constructor initializes instance and class variables. If there is no explicit initialization of fields, those are set as follows: 0 for numbers; null for objects; false for boolean and ‘\0’ for character.

Here are examples:
Constructor.java: to show how consturctor is used.

 class ClassA{//has two explicit constructors---one with parameters and the other without them 
	private int m;
	private double n;
	ClassA(int m, double n){//Constructor's name is the same as that of the class
		this.m=m; this.n=n;
		//NO return statement
	}
	ClassA(){
		this(1,1.0);//Calling a constructor must be at the top of constructor.
		System.out.println("Calling constructor must be at the top of constructor.");
	}
}
class Constructor {
	public static void main(String args[]){
		ClassA c1 = new ClassA(1,1.0);//Constructor is called to make an instance. 
		System.out.println();
		ClassA c2 =new ClassA();
	}
}

Constructor2.java: to show how primitives are initialized in a constructor.

class ClassB{//has no explicit constructor
   int a;
	short b;
	double c;
	boolean d;
	String e;
	char f;
	void show(){
		System.out.println("int a="+a);
		System.out.println("short b="+b);
		System.out.println("double c="+c);
		System.out.println("boolean d="+d);
		System.out.println("String d="+e);
		if(f=='\0') System.out.println("char f=\'\\0\'");
	}
}
class Constructor2 {
   public static void main(String args[]){
      ClassB c = new ClassB();//implicitly defined constructor
		c.show();
   }
}
//int a=0
//short b=0
//double c=0.0
//boolean d=false
//String d=null
//char f='\0'

Go to Table of Contents