Monthly Archives: April 2014

Non-inheritable and non-instantiable class

In this post we would see how to design a class which can neither be instantiated nor inherited. Java language has two modifiers/keywords which provide the individual functionality. A class declared as final cannot be inherited and a class declared as abstract cannot be instantiated. It may seem that if we combine the two we would get a class which is Non-inheritable and non-instantiable, but, if we try the following:

final abstract class Base{}

The compiler would given the error “illegal combination of modifiers: abstract and final”. This happens because the modifiers are conflicting in nature, a class which is final cannot be inherited and a class which is abstract must be inherited. Hence, the compiler prohibits the use of the two simultaneously.

Let us first concentrate on designing a class which cannot be instantiated. We have already seen that declaring a class as abstract is not valid solution. The other way is to define a private constructor. Note that whenever an object is created constructor is invoked. If we define a constructor as private it cannot be accessed from outside the class but the rules requires that a constructor must be invoked at the time of instantiation. In this way if there is a private constructor inside a class, it’s object cannot be instantiated from outside the class. Thus, the following code would prevent an object to be instantiated from outside the class:

class Base{
   private Base(){}
}
class Dummy{
    public static void main( String args[] ){
        new Base();
    }
}

The above Java program when executed would give an error Base() has private access in Base. Now let us try to extend or inherit the class Base as follow:

class Base{
   private Base(){}
}
class Dummy extends Base{
    
}

The above program would result in the error “Base() has private access in Base”. It may seem that the job is done, but, the above would not work of the class being extended is an inner class of Base as follows:

class Base{
   private Base(){}
   class Dummy extends Base{}
}

In order to make the code work even for inner class we must make the enclosing class, that is the class Base as final. The final program for designing a Non-inheritable and non-instantiable class would be as follows:

final class Base{
   private Base(){}
}
class Dummy extends Base{
    
}