Posts

Showing posts from 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

Diamond Problem in Multiple Inheritance in OOPS

Image
The diamond problem occurs when two super classes of a class have a common base class.  Suppose there are four classes A, B, C and D. Class B and C inherit class A. Now class B and C contains one copy of all the functions and data members of class A. Class D is derived from class B and C. Now class D contains two copies of all the functions and data members of class A. One copy comes from class B and another copy comes from class C. Let’s say class A has a function with name display(). So class D have two display() functions as I have explained above. If we call display() function using class D object then ambiguity occurs because compiler gets confused that whether it should call display() that came from class B or from class C. If you will compile above program then it will show error. This kind of problem is called diamond problem as a diamond structure is formed (see the image). That is why major programming languages like C#, Java and Delphi don't have multiple inheritance bec