Skip to main content

Class with a private constructor

In "Cracking the Coding Interview" by J. Laakmann McDowell, I found an interesting question concerning the influence of private constructors on inheritance in Java. I know that this is not forbidden in Java, so I'm wondering in which cases it might be useful.
In Java, it is not possible to inherit a class with a private constructor. But if this class is internal, the parent class can access all private methods of internal classes. Thus, the inheritance of internal classes with private constructors is possible in the scope of the parent class. I think this is useful for implementing Singletons.

I want to demonstrate these cases in the following example:
import java.util.*;
import test.*;

public class Main {
    class PrivateClassA {
        private PrivateClassA() {
                System.out.println("Private constructorA");
            } 
        
    }

    /* PrivateClassB inherits the class with the private constructor */
    class PrivateClassB extends PrivateClassA  {
        public PrivateClassB() {
            super();
            System.out.println("Private constructorB");
        }
    }
    
    public static void main(String[] args) {
        Main main = new Main();
        PrivateClassB bInstance = main.new PrivateClassB();
        PrivateClassD dInstance = new PrivateClassD();
    }
}
package test;
import java.util.*;

public class PrivateClassC {
  private PrivateClassC() {
    System.out.println("Init class C");
  }
}
package test;
import java.util.*;

// PrivateClassC cannot be inherited because this class has a private constructor


public class PrivateClassD /* extends PrivateClassC */{
  public PrivateClassD() {
    // The Inheritance of private constructor causes an exception
    // super();
    System.out.println("Init class D");
  }
}

Comments

Popular posts from this blog

An interview exercise #1

An exercise from Amadeus interview /* Input: number 2543 Output: index of the digit that is needed to remove to get the maximum number from the original number [0]2: 543 -> It is a maximum, so answer is 0 [1]5: 243 [2]4: 253 [3]3: 254 */ function findIndexToGetMax (n) { if (n < 10 ) return null ; let digits = n. toString (). split ( '' ). map (d => parseInt (d)); let current_n = digits[ 0 ]; let pos_n = 0 ; for ( let i = 1 ; i < digits.length; i++) { if (current_n < digits[i]) { return pos_n; } else { current_n = digits[i]; pos_n = i; } } return pos_n; } let tests = { 2526 : 0 , 9526 : 2 , 19 : 0 , 10 : 1 , 12345 : 0 , 54321 : 4 } ; let expected_n; let testedValue_n; for ( let key_s in tests) { if (!tests. hasOwnProperty (key_s)) continue ; expected_n = tests[key_s]; testedValue_n = findIndexToGetMax ( parseInt (key_s)); if (testedValue_n != expected_n) { console. log ( ...