本文介绍了Java——私有构造函数 vs final 等等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个类的所有构造函数都声明为私有.

Suppose there is a class with all of its constructors declared as private.

例如:

public class This {
    private This () { }

    public someMethod( ){
    // something here
    }
   // some more-- no other constructors
}

据我所知,将所有构造函数设为私有类似于将This"类声明为 final——因此它无法扩展.

From what I know, making all constructors private is similar to declaring the class "This" as final-- so that it can't be extended.

然而,我收到的 Eclipse 消息给我的印象是这是可能的——一个全构造函数私有类可以扩展.看看这个:

However, the Eclipse messages i'm getting are giving me the impression that this is possible-- an all-constructors-private class can be extended. Take a look at this:

当我尝试用类似的东西扩展这个类时

When I attempt to extend this class with something like

public class That extends This {
    ...
}

Eclipse 给我一个错误:隐式超级构造函数 This() 对于默认构造函数不可见.必须定义一个显式构造函数."

Eclipse giving me an error that: "Implicit super constructor This() is not visible for default constructor.Must define an explicit constructor."

当我定义自己的构造函数时:

When i define a constructor of its own:

public class That extends This {
    That () {..}
    ...
}

这次我得到:"隐式超级构造函数 This() 对于默认构造函数不可见.必须显式调用另一个构造函数."

有没有办法解决这个问题——扩展一个所有构造函数都是私有的类?

Is there a way to get around this-- of extending a class of which all constructors are private?

如果是,如何?

如果不是,阻止一个类被扩展有什么区别i.) 将其构造函数设为私有,以及ii.) 将其定义为 final?

if no, what's the difference between stopping a class from being extended byi.) making its constructors private, andii.) defining it as final?

注意:我看到了可以在Java 是私有的吗? 以及其他一些讨论.

Note: i saw Can a constructor in Java be private? among some other discussions.

推荐答案

一个带有私有构造函数的类不能被实例化,除了同一个类中的表单.这使得从另一个类扩展它变得无用(可能,但不会编译).

A class with private constructors cannot be instantiated except form inside that same class. This make it useless (possible, but will not compile) to extend it from antoher class.

这并不意味着它根本不能被子类化,例如在内部类中你可以扩展和调用私有构造函数.

This does not mean it cannot be subclassed at all, for example among inner classes you can extend and call the private constructor.

这篇关于Java——私有构造函数 vs final 等等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:38