Extend classes with private constructor

Asked

Viewed 711 times

13

Because I can’t extend classes with private builder?

Consindo the classes To:

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’t extend To?

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

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

3 answers

10


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

B.java

import static meu.pacote.A.*;

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

If you really need to inherit, use a builder protected as suggested by @Gypsy Morrison Mendez. Or, if the classes are in the same package, a "package protected" (i.e. no modifier) - as this prevents any class outside the package from inheriting A. You can still mark it as abstract (preventing instantiation) or perhaps making an exception in the constructor (preventing the instantiation of subclasses), if it deems necessary to make its code "idiot-proof". At your discretion...

8

Because this goes against the formal definition of protection methods of classical object orientation theory. If a member is private, it cannot be accessed by any class other than the class itself.

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

  • 1

    As far as I know proteced is an access modifier that makes visible the class and/or attribute for all other classes and subclasses THAT BELONG TO THE SAME PACKAGE. Edit: Source http://docs.oracle.com/javase/tutorial/javaO/accesscontrol.html

  • 1

    In this case it is not worth changing the answer, because the question of the package is Java’s own, and I explained talking about the general theory of object orientation.

1

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.