Pages

Thursday 5 October 2017

Use of Private Constructor in OOPS

If we set access specifier of a constructor to private, then that constructor can only be accessed inside the class. A private constructor is mainly used when you want to prevent the class instance from being created outside the class. 

This is mainly in the case of singleton class. Singleton classes are employed extensively in concepts like Networking and Database Connectivity. Using private constructor we can ensure that no more than one object can be created at a time. 

Example of Private Constructor in a Singleton Class

public class SingletonClass
{
    public static SingletonClass singletonClass;

    private SingletonClass() 
    {
    }

    public static SingletonClass getInstance() 
    {
        if(singletonClass == null) 
        {
            singletonClass = new SingletonClass();
        }
        return singletonClass;
    }
}

A class with private constructor cannot be inherited.

If we don’t want a class to be inherited, then we make the class constructor private. So, if we try to derive another class from this class then compiler will flash an error. Why compiler will flash an error? 

We know the order of execution of constructor in inheritance that when we create an object of a derived class then first constructor of the base call will be called and then constructor of derived class. Since base class constructor is private, hence, derived class will fail to access base class constructor.

We can also use sealed class to stop a class to be inherited. Sealed class provide more flexible and readable way to stop inheritance.

No comments:

Post a Comment

About the Author

I have more than 10 years of experience in IT industry. Linkedin Profile

I am currently messing up with neural networks in deep learning. I am learning Python, TensorFlow and Keras.

Author: I am an author of a book on deep learning.

Quiz: I run an online quiz on machine learning and deep learning.