How to call constructors in JAVA during constructor overloading?
Answers
Short note on constructor overloading:
⇒ In the same class, if we define multiple constructors with different parameters, then it is called constructor overloading. Each constructor performs different task.
⇒ When we don't define any constructor, then the compiler will create a default constructor.
⇒ In java, Constructor is used to initialize the object state.
⇒ Constructor name should be similar to class name.
⇒ Constructor overloading follows 3 defined rules:
(a) Based on number of parameters
(b) Based on name of parameters
(c) Based on order or place of parameters.
A small program of Constructor Overloading:
class Demo
{
String hello;
int num;
int num1;
Demo(String str, int d)
{
hello = str;
num = d;
}
Demo(String str, int d, int e)
{
hello = str;
num = d;
num1 = e;
}
void PrintVariables()
{
System.out.println("Name: "+hello+" Age: "+num+" Marks: "+num1);
}
public static void main(String args[])
{
Demo d = new Demo("John", 28);
Demo d1 = new Demo("Rock", 35, 100);
d.PrintVariables();
d1.PrintVariables();
}
}
Output:
Name : John Age : 28 Marks : 0
Name : Rock Age : 35 Marks : 100.
Hope this helps!
Answer:
:
class Demo
{
String hello;
int num;
int num1;
Demo(String str, int d)
{
hello = str;
num = d;
}
Demo(String str, int d, int e)
{
hello = str;
num = d;
num1 = e;
}
void PrintVariables()
{
System.out.println("Name: "+hello+" Age: "+num+" Marks: "+num1);
}
public static void main(String args[])
{
Demo d = new Demo("John", 28);
Demo d1 = new Demo("Rock", 35, 100);
d.PrintVariables();
d1.PrintVariables();
}
}
Output:
Name : John Age : 28 Marks : 0
Name : Rock Age : 35 Marks : 100.
Read more on Brainly.in - https://brainly.in/question/6086771#readmore