Java Constructor

  1. Syntax
  2. Contructor Creation in Java
  3. Constructor Overloading in Java
  4. Create More Constructors for More Classes

Note
Here I am using,
OS : Linux (Ubuntu 12.04)
IDE : Eclipse Tool
Eclipse : Juno (Version 4.2.0)
Package : Default package

A. Syntax


Constructor

class ClassName {
 
	ClassName() {
 
		// Statement..
	}
}
 
class MainClass {
 
	public static void main(String args[]) {
 
		ClassName objName = new ClassName();
		// We don't want to call the Constructor..
		// It will automatically call when we create object for that class..
	}
}





B. Contructor Creation in Java


Constructor_Ex1.java

public class Constructor_Ex1 {
	
	int a, b, c;
	
	Constructor_Ex1() {
		
		System.out.println("Constructor - Simple Example");
		
		a = 11;
		b = 20;
		c = a + b;
	}
	
	void display() {
		
		System.out.println("The Addition is : " + c);
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Constructor_Ex1 obj = new Constructor_Ex1();
		
		obj.display();
	}
}

Sample Output

Constructor - Simple Example
The Addition is : 31




C. Constructor Overloading in Java


Constructor_Ex2.java

public class Constructor_Ex2 {
	
	Constructor_Ex2() {
		
		System.out.println("Constructor Overloading Example");
	}
	
	Constructor_Ex2(int x) {
		
		System.out.println("Constructor int - " + x);
	}
	
	Constructor_Ex2(float x) {
		
		System.out.println("Constructor float - " + x);
	}
	
	Constructor_Ex2(char x) {
		
		System.out.println("Constructor char - " + x);
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Constructor_Ex2 obj1 = new Constructor_Ex2();
		Constructor_Ex2 obj2 = new Constructor_Ex2(111);
		Constructor_Ex2 obj3 = new Constructor_Ex2((float) 11.20);
		Constructor_Ex2 obj4 = new Constructor_Ex2('B');
	}
}

Sample Output

Constructor Overloading Example
Constructor int - 111
Constructor float - 11.2
Constructor char - B




D. Create More Constructors for More Classes


Constructor_Ex3.java

public class Constructor_Ex3 {
	
	Constructor_Ex3() {
		
		System.out.println("More Classes and More Constructors");
	}
}
 
class SubClass1 {
	
	SubClass1() {
		
		System.out.println("SubClass - 1");
	}
}
class SubClass2 {
	
	SubClass2() {
		
		System.out.println("SubClass - 2");
	}
}
 
class MainClass {
	
	public static void main(String args[]) {
		
		Constructor_Ex3 obj1 = new Constructor_Ex3();
		SubClass1 obj2 = new SubClass1();
		SubClass2 obj3 = new SubClass2();
	}
}

Sample Output

More Classes and More Constructors
SubClass - 1
SubClass - 2






SHARE THIS PAGE



product 2

product 3

Feedbacks : balaji.scz@gmail.com