Constructor
Constructor
What is a constructor?
•The name of the constructor must be the same as the class name.
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object
of a class is created. It can be used to set initial values for object attributes:
// Outputs 5
The code above shows a class called Student with three attributes – firstName, lastName, and age.
We will assume that the class is supposed to be a sample for registering students. Recall that the
three attributes do not have any values so none of the information is hard coded.
Now we will use constructors to create a new instance of our Student object. That is:
public class Student {
String firstName;
String lastName;
int age;
//Student constructor
public Student(){
firstName = “Ankit";
lastName = “Mishra";
age = 20;
}
A default constructor is a constructor created by the compiler if we do not define any constructor(s) for a class. Here is an example:
myStudent.firstName = "Ankit";
myStudent.lastName = "Mishra";
myStudent.age = 20;
System.out.println(myStudent.age);
//20
System.out.println(myStudent.firstName);
Output
//Ankit 20
} Ankit
}
Java compiler automatically creates a default constructor (Constructor with no arguments) in
case no constructor is present in the java class. Following are the motive behind a default
constructor.
Output
Parameterized Constructor called.
num = 10
str = SCHEME
Constructor Overloading
•In Java, it is possible to create methods that have the same
name, but different parameter lists and different definitions.
This is called method overloading.
The destructor is the opposite of the constructor. The constructor is used to initialize objects while the destructor is
used to delete or destroy the object that releases the resource occupied by the object.
Syntax:
protected void finalize throws Throwable()
{
//resources to be close
}
Example of Destructor
public class DestructorExample
{ Output:
public static void main(String[] args)
{
DestructorExample de = new DestructorExample ();
de.finalize();
de = null; Object is destroyed by the Garbage Collector
System.gc(); Inside the main() method
System.out.println("Inside the main() method"); Object is destroyed by the Garbage Collector
}
protected void finalize()
{
System.out.println("Object is destroyed by the Garbage
Collector");
}
}
1. Write a java programme to print the student name, department, and roll
no using default constructor and parameterized constructor.
(student name: Ankit, Department: SCHEME, Roll No. 1)