Interview questions on constucture

                                                    ON CONSTRUCTOR 

 1) What is constructor chaining?

Constructor Chaining is a technique of calling another constructor from one constructor. this() is used to call same class constructor where as super() is used to call super class constructor.

2) Can we call sub class constructor from super class constructor?

No .we can't call sub class constucture from parent class constucture

3) What is No-arg constructor?

Constructor with no  arguments is called no-arg constructor. Default constructor in java is always a no-arg constructor.

4) What is the use of private constructor?

Private constructors are used to restrict the instantiation of a class. When a class needs to prevent other classes from creating it objects then private constructors are suitable for that . A  good  use of private constructor is in singleton pattern. This ensures only one instance of a class exist at any point of time. Here is an example of singleton pattern using private constructor.


class MyClass
{
    private static MyClass object = null;
    private MyClass()
    {
        //private constructor
    }
    public MyClass getObject()
    {
        if(object == null)
        {
            object = new MyClass();   //Creating object using private constructor
        }
        return object;

    }

}

5) What will happens if we keep return type for a constructor?

It will be treated as a normal method. But compiler gives a warning saying that method has a constructor name.

6) When do we need to Constucture overloading?
Whenever we  need to initializing an object in different ways. This can be done using constructor overloading. Different constructors can do different work by implementing different line of codes and are called based on the type and no of parameters passed.



7) what is constructe 

Constucture is used to initialize the object .



Comments

Popular posts from this blog

OBJECT ORIENTED CONCEPTS

Arrays programms