Practical-20
Write a java program which implements the Overloading of Constructors.
Introduction
Java Programming language is an object-oriented language, which is designed to be simple and easy to understand. It is a language that emphasizes the ability to express code easily with the help of its comprehensive library. Overloading of constructors is a process where a constructor can be overloaded in terms of its parameters so that the same constructor can be used to initialise objects in different ways.
Code
class ConstructorOverloading
{
String name;
int id;
String course;
float fees;
ConstructorOverloading() // default constructor
{
name="TOM";
id=101;
course="JAVA";
fees=18000;
}
ConstructorOverloading(String n, int i) //parameterized constructor
{
name=n;
id=i;
}
ConstructorOverloading(String n, int i, String c, float f) //parameterized constructor
{
name=n;
id=i;
course=c;
fees=f;
}
void display(){
System.out.println("Name is:"+name +"\n"+"ID is:"+id +"\n"+"Course is:"+course +"\n"+"Fees is:"+fees);
}
public static void main(String[] args)
{
ConstructorOverloading obj1 = new ConstructorOverloading();
obj1.display();
ConstructorOverloading obj2 = new ConstructorOverloading("JERRY",102);
obj2.display();
ConstructorOverloading obj3 = new ConstructorOverloading("ROBIN",103,"C++",25000);
obj3.display();
}
}
Output
Name is: TOM
ID is: 101
Course is: JAVA
Fees is: 18000.0
Name is: JERRY
ID is: 102
Course is: null
Fees is: 0.0
Name is: ROBIN
ID is: 103
Course is: C++
Fees is: 25000.0
The above code is an example of constructor overloading where the same class can have multiple constructors differing in parameters. Different objects of the same class can thus be initialised with different values. The constructor without any parameters is known as the default constructor, and it usually assigns default values to the fields. The constructors taking parameters are known as parameterised constructors.