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
In short, Constructor with different arguments is called Constructor overloading.
Example 1:
class Reverse
{
Reverse(int a)
{
//code to reverse a number
}
Reverse(String str)
{
//code to reverse a String
}
}
Example 2:
In short, Constructor with different arguments is called Constructor overloading.
Example 1:
class Reverse
{
Reverse(int a)
{
//code to reverse a number
}
Reverse(String str)
{
//code to reverse a String
}
}
Example 2:
class Demo{ int value1; int value2; Demo(){ value1 = 10; value2 = 20; System.out.println("Inside 1st Constructor"); } Demo(int a){ value1 = a; System.out.println("Inside 2nd Constructor"); } Demo(int a,int b){ value1 = a; value2 = b; System.out.println("Inside 3rd Constructor"); } public void display(){ System.out.println("Value1 === "+value1); System.out.println("Value2 === "+value2); } public static void main(String args[]){ Demo d1 = new Demo(); Demo d2 = new Demo(30); Demo d3 = new Demo(30,40); d1.display(); d2.display(); d3.display(); }}
No comments:
Post a Comment