Constructor Overloading


Constructor overloading is a condition when multiple constructors are created in same class.

Each constructor should have different input parameters.

It is same as method overloading but with case of constructors.


eg in following program demonstrates constructor overloading


1. myClass.java:

public class myClass {
	public static void main(String[] args) {
		
		next test=new next();
		next test1=new next(11);
		next test2=new next(11,22);
		next test3=new next(11,22,33);
		
		
		System.out.println("No Input = "+test.Volume());
		System.out.println("1 Input = "+test1.Volume());
		System.out.println("2 Input = "+test2.Volume());
		System.out.println("3 Input = "+test3.Volume());
	}

}

2. next.java:
public class next {

	int l,b,h;
	
	public next() {
		this.l=10;
		this.b=20;
		this.h=30;
	}
	

	public next(int len) {
		this.l=len;
		this.b=20;
		this.h=30;
	}
	

	public next(int len,int br) {
		this.l=len;
		this.b=br;
		this.h=30;
	}
	
	public next(int len,int br,int he) {
		this.l=len;
		this.b=br;
		this.h=he;
	}
	
	public int Volume() {
		return (this.l * this.b + this.h);
	}
	
}

output of following program:
No Input = 230
1 Input = 250
2 Input = 272
3 Input = 275



Related Tutorials