214k views
5 votes
Demonstrate constructor overloading by both declaring relevant constructors of your choice and invoking them. [

User Orjan
by
5.4k points

1 Answer

5 votes

Answer:

Constructor overloading means constructor having same name but different signature

Parameter of constructor are depend upon

Number of parameter

Type of parameter.

Sequence of parameter

When we create an object of an class the compiler determines which type of constructor is call by comparing its signature of constructor.

For example:

Following are the constructor overloading program in java

class abc // creating class

{

int r;

String name;

abc(int r1) // Constructor 1

{

r = r1;

System.out.println(r);

}

abc(String n1) // Constructor 2

{

name=n1;

System.out.println(name);

} }

class Main // main class

{

public static void main(String[] args) // main method

{

abc ob=new abc(1); // object 1

abc S2 = new abc("Sumit"); // object 2

}

}

Output:

1

Sumit

In this program, we have two constructors.

object 1 will call constructor 1 because the signature of constructor 1 is matched to the statement 1.

object 2 will call constructor 2 because the signature of constructor 2 is matched to the statement 2

User Horace Heaven
by
4.9k points