JAVA Constructor and Destructor - Java
18223
Arnab De
01/07/2017
What is Constructor?[ICSE 2014]
Constructor is method in a class which is initialised object variables, when an object is create.
What are the characteristics of a constructor?
- A constructor has the same name as the class name.
- A constructor has no return type, not even void.
- Access specifies of the constructors are generally public.
- A constructor is automatically called on object creation.
When is a constructor called?[ICSE 2014]
A constructor is called automatically during object creation.
How many Types of constructor possible in java?
There are three types of constructor possible in java
- Default Constructor: If programmers do not specify any constructor, then compiler automatically define a constructor called default constructor. If programmers specify any constructor then supply of the default constructor is stop.
- Null Constructor: This type of the constructor has not received any parameter. It is generally initialised the objects with default values.
- Parameterised Constructor: This type of the constructor has received one or many parameters. It is generally initialised the objects with customised values.
What is the difference between a default constructor and a null constructor?
Null constructor is defined by the programmers and initial values are also determined by the programmers. But default constructor is supplied by constructors it doesn’t accept any parameters and initial values are not defined by programmers.
What is the difference between a default constructor and a parameterised constructor?
A default constructor doesn’t accept any parameters. A parameterised constructor accepts parameters.
What does the default constructor provided by the compiler do?
The default constructor provided by the compiler initializes all instances variables to their default values. It initialises integers to 0, floating point numbers to 0.0, boolean values to false and objects to null.
What is a destructor?
A destructor is a method which is executed when the object is removed from computer’s memory.
Explain the concept of constructor overloading with an example. [ICSE 2011]
A class can have more than one constructor with different singature. This is known as constructor overloading.
Example:
class Car
{
int color;
public Car() { color = -1;}
public Age(int cl) {color = cl;}
}