Extend classes with private constructor

13

Why can not I extend classes with private constructor?

Getting the A: classes

public class A {
    private A(){}
    public static void limao(){}
}

and B:

public class B extends A {
    private B(){}
    public static void banana(){}
}

Why B can not extend A ?

There is no default constructor available my.package.name.A

My goal is to have some classes that contain only static members and would like to ensure that they are used in the correct way (without instances) but also inherit from other classes because they have methods in common. Currently I do this in C # through static classes but I can not apply something similar on my Android project.

    
asked by anonymous 25.02.2014 / 00:23

3 answers

10

If all methods are static, why inherit from the class? You can simply, in class B , import all methods of A so that you can continue to call them without having to A.metodo .

B.java

import static meu.pacote.A.*;

public class B {
    private B(){}
    public static void banana(){
        limao();
    }
}

If it is even necessary to inherit, use a protected constructor as suggested by @Cigano Morrison Mendez. Or, if the classes are in the same package, a "package protected" (i.e. without modifier) - because this prevents any class outside the inherit package from A . You can still mark it as abstract (preventing instantiation) or perhaps throw an exception in the constructor (preventing the instantiation of subclasses) if you feel it necessary to make your code foolproof. It's up to you ...

    
25.02.2014 / 01:23
8

Because this goes against the formal definition of method protection of classical object-oriented theory. If a member is private , it can not be accessed by any other class than the class itself.

For this case, use protected so that the constructor can be accessible by the classes that extend its class A.

    
25.02.2014 / 00:28
1

Because the constructor was declared private in A and B can not access private members, only public or protected. When you declare a constructor as private no other class will see it being impossible to inherit from it or instantiate it in another class.

    
25.02.2014 / 15:01