Constructor in Java

Constructors in Java

What is a constructor?

Ans: A constructor is a special member method that is automatically called when an instance of a class is declared. A constructor is called when an object of the class is created.
It is a function.
A constructor must have the same name as the class name.
It has no return type not even void.
It is called when the object of the class is created.
It is used to initialize the instance variables.
These methods can only be executed at the time of the creation of an object, it is not possible to use them later.
Remember that Java creates the constructor without arguments automatically, however, if we have added a constructor with arguments, then Java will no longer add this constructor for us and it is our responsibility to add it if we are going to need it, in fact for good practice, we should always add it that we defined a constructor with arguments. 



Why do we need a constructor as a class member?

Ans: We need a constructor as a class member to initialize the value for a class variable and to create objects.

Why should a constructor be defined as public?


Ans: A constructor should be defined in the public section of a class so that its objects can be created in any function.

What are the types of Constructors used in a class?

Ans: The different types of constructors are as follows:
Default Constructors.
Parameterized Constructor.
Copy Constructors.

 What is a default constructor? Why a default a constructor is called so?


Ans: If a class has no constructor defined, the compiler creates a constructor called default constructor which as no arguments. It initializes the data members by a default value.

Explain the Parameterized constructor?

Ans: The constructors which can take different parameters are referred to as Parameterized Constructors.
 Example:
class  Summation
{
   int x,y,z;
   public Summation(int x,int y)
   {
            this. x=x;
            this.y=y;
   }
   int sum()
   {
            z=x+y;
   }
}

What is a copy, constructor?


A copy constructor creates a temporary object of a class. It is used to copy the initialize values of the instance variables of an object to the instance variables of another object.

Mention some characteristics of constructors.

Ans: The special characteristics of constructors are:
The name of the constructor is the same as that of class
Constructors should be declared in the public section of the class.
They have invoked automatically when an object of the class is created.
They do not have any return type not even void.
They can accept arguments.
A class can have more than one constructor.
Default constructor does not accept parameters.
Constructor can be overloaded.
If no constructor is present in the class the compiler provides a default constructor.

State the difference between Constructor and Method.

Ans:
The constructor name and the class name should be the same whereas a Method can have any name
The constructor has no return type but a method has any type such as int, double, float, etc.
Invoked as soon as the object is created whereas the method invoked after the object is created.
Can be called only once but the method can call any number of times.
Constructors cannot be abstracted, final, static or synchronized but methods can be abstracted, final, static or synchronized
It is used to initialize whereas it is used to do any operation.

How compiler and JVM can differentiate constructor and method definitions of both have the same class name?

It differentiates by using return type, if there is a return type it is considered as a method else it is considered as a constructor.

Can we call subclass constructor from superclass constructor?


One word answer NO, We cannot call subclass constructor from a superclass constructor.

What is constructor overloading?


Ans: Possessing more than one constructor with a different signature by a class is known as constructor overloading.

When do we need Constructor Overloading? Or why do we overload constructors in Java?

Ans:
Let us consider the following example
Class Summation
{
   int a, b;
  Summation ()
   {
a=10;
b=20
    }
  Summation (int m, int n)
   {
a=m;
b=n;
    }
   Summation (Summation x)
   {
a=x.a;
b=x.b;
    }
In the above program, three constructors are used with different types of parameters, which means we can initializing an object in different ways. This can be done using constructor overloading. Distinctive constructors can do different work by executing different codes and are called based on the type and no of the parameters passed. According to the situation, a constructor is called with a specific number of parameters among overloaded constructors.

Do we have destructors in Java?

No. Java has its own garbage collector inbuilt and Garbage Collector takes care of clearing up memory allocated to object.

Full Example of Constructor
In this program autono and km is initialize in the constructor.
import java.io.*;
public class Automobile
{
    int autono,km;
    double rate;
    String name;
    Automobile()   // Constructor Method
    {
        autono=0;
        km=0;
    }
    void input()throws IOException    // Input Method
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter automobile no, km and name:");
        autono=Integer.parseInt(br.readLine());
        km=Integer.parseInt(br.readLine());
        System.out.println("Enter Name:");
        name=br.readLine();
        
    }
    void calculate()                          // Calculate method
    {
        if(km<=1)
         rate=25;
        else if(km>1 && km<=6)
         rate=25+10;
        else if(km>6 && km<=12)
         rate=25+10+15;
        else if(km>12 && km<=18)
         rate=25+10+15+20;
        else
         rate=25+10+15+20+25;
        }
        void display()
        {
            System.out.println("Automobile no=" + autono);
            System.out.println("Name=" + name);
            System.out.println("Rate=" + rate);
        }
        public static void main(String args[])throws IOException
        {
            Automobile ob=new Automobile();
            ob.input();
            ob.calculate();
            ob.display();
        }            
}
Sample Output
Enter automobile no, km and name:
1002
75
Enter Name:
Maruti
Automobile no=1002
Name=Maruti
Rate=95.0



Advance Java Programming


Become A Professional Java Developer From Scratch

SHARE THIS
Previous Post
Next Post