Aim
To write a program for demonstrating constructors.
Theory
A constructor is a special method which has the same name as class name and that is used to initialize the objects (fields of an object) of a class. A constructor has the following characteristics:
- Constructor has the same name as the class in which it is defined.
- Constructor doesn’t have a return type, not even void. Implicit return type for a constructor is the class name.
- Constructor is generally used to initialize the objects of a class.
Syntax for creating a constructor is as shown below:
ClassName( [Parameters List] )
{
//Code of the constructor
}
A constructor is invoked (called) automatically whenever an object is created using the new keyword. Java automatically invokes the default constructor which initializes all the fields to their default values.
Based on the number of parameters and type of parameters, constructors are of three types:
- Parameter less constructor or zero parameter constructor
- Parameterized constructor
- Copy constructor
Pseudo code/Steps
- Create a class Student.
- Create a parameter less constructor, parameterized constructor, and copy constructor inside Student
- Create class Driver.
- Create objects for Student class and invoke all 3 types of constructors.
Program
Following Java program demonstrates different types of constructors:
class Student
{
String name;
int age;
char grade;
Student()
{
name = "";
age = 0;
grade = '0';
}
Student(String n, int a, char g)
{
name = n;
age = a;
grade = g;
}
Student(Student t)
{
name = t.name;
age = t.age;
grade = t.grade;
}
void getDetails()
{
System.out.println("Student name is: " + name);
System.out.println("Student age is: " + age);
System.out.println("Student grade is: " + grade);
}
}
class Driver
{
public static void main(String args[])
{
Student s1 = new Student();
Student s2 = new Student("Ramesh", 19, 'A');
s2.getDetails();
Student s3 = new Student("Suresh", 19, 'B');
s3.getDetails();
Student s4 = new Student(s2);
s4.getDetails();
}
}
Input and Output:
Student name is: Ramesh
Student age is: 19
Student grade is: A
Student name is: Suresh
Student age is: 19
Student grade is: B
Student name is: Ramesh
Student age is: 19
Student grade is: A
Result
The concept of constructor is understood and demonstrated successfully.

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply