Constructor Overloading:
public class ConstructorOverloadingExample {
int x;
int y;
int z;
public ConstructorOverloadingExample() {
x = 1;
y = 1;
z = 1;
}
public ConstructorOverloadingExample(int a, int b) {
x = a;
y = b;
z = 1;
}
public ConstructorOverloadingExample(int a, int b, int c) {
x = a;
y = b;
z = c;
}
public ConstructorOverloadingExample(int a) {
x = a;
y = 1;
z = 1;
}
public int getIntValues() {
return x * y * z;
}
public static void main(String a[]) {
ConstructorOverloadingExample i = new ConstructorOverloadingExample();
ConstructorOverloadingExample j = new ConstructorOverloadingExample(10);
ConstructorOverloadingExample k = new
ConstructorOverloadingExample(10,20, 30);
ConstructorOverloadingExample l = new ConstructorOverloadingExample(10,
20);
int q;
q = i.getIntValues();
System.out.println("area of room i is "+ q);
q = j.getIntValues();
System.out.println("area of room j is "+ q);
q = k.getIntValues();
System.out.println("area of room k is "+ q);
q = l.getIntValues();
System.out.println("area of room l is "+ q);
}
}
*************************************************
- Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.
- The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.
Example for Constructor Overloading:
*************************************************public class ConstructorOverloadingExample {
int x;
int y;
int z;
public ConstructorOverloadingExample() {
x = 1;
y = 1;
z = 1;
}
public ConstructorOverloadingExample(int a, int b) {
x = a;
y = b;
z = 1;
}
public ConstructorOverloadingExample(int a, int b, int c) {
x = a;
y = b;
z = c;
}
public ConstructorOverloadingExample(int a) {
x = a;
y = 1;
z = 1;
}
public int getIntValues() {
return x * y * z;
}
public static void main(String a[]) {
ConstructorOverloadingExample i = new ConstructorOverloadingExample();
ConstructorOverloadingExample j = new ConstructorOverloadingExample(10);
ConstructorOverloadingExample k = new
ConstructorOverloadingExample(10,20, 30);
ConstructorOverloadingExample l = new ConstructorOverloadingExample(10,
20);
int q;
q = i.getIntValues();
System.out.println("area of room i is "+ q);
q = j.getIntValues();
System.out.println("area of room j is "+ q);
q = k.getIntValues();
System.out.println("area of room k is "+ q);
q = l.getIntValues();
System.out.println("area of room l is "+ q);
}
}
*************************************************
In this example we have created four constructors with different number of input parameters. This is constructor over loading.
No comments:
Post a Comment