使用私有构造函数扩展类 [英] extends of the class with private constructor

查看:120
本文介绍了使用私有构造函数扩展类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下代码:

class Test {
    private Test() {
        System.out.println("test");
    }

}

public class One extends Test {

    One() {
        System.out.println("One");
    }

    public static void main(String args[]) {

        new One();
    }
}

当我们创建一个对象一个,最初称为父类构造函数 Test()。但因为 Test()是私有的 - 我们得到一个错误。
多少是一个很好的例子,一种解决这种情况的方法?

When we create an object One, that was originally called the parent class constructor Test(). but as Test() was private - we get an error. How much is a good example and a way out of this situation?

推荐答案

你必须创建一个可用的( protected public 或默认)super构造函数能够扩展 test

There is no way out. You have to create an available (protected, public or default) super constructor to be able to extend test.

这种表示法通常用于实用程序类或单例,其中您不希望用户创建自己

This kind of notation is usually used in utility classes or singletons, where you don't want the user to create himself an instance of your class, either by extending it and instanciating the subclass, or by simply calling a constructor of your class.

当你有一个的时候,你的类的一个实例,通过扩展它和实例化子类,或者通过简单地调用你的类的构造函数。只有 private 构造函数的类,还可以将更改为<$ c $

When you have a class with only private constructors, you can also change the class to final because it can't be extended at all.

另一个解决方案是在 test 中创建一个方法,创建 test 的实例,并委托来自 / code>到测试实例。这样,您不必扩展 test

Another solution would be having a method in test which create instances of test and delegate every method call from One to a test instance. This way you don't have to extend test.

class Test {
    private Test() {
        System.out.println("test");
    }
    public static Test getInstance(){
        return new Test();
    }
    public void methodA(){
        //Some kind of implementation
    }
}

public class One {
    private final Test test;
    One() {
        System.out.println("One");
        test = Test.getInstance();
    }

    public void methodA(){
        test.methodA();
    }

    public static void main(String args[]) {
        new One();
    }
}

这篇关于使用私有构造函数扩展类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆