Java - 私有构造函数vs final和更多 [英] Java -- private constructor vs final and more

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

问题描述

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



例如:

  public class This {
private这个(){}

public someMethod(){
//这里的
}
//更多 - 没有其他构造函数
}

从我知道,使所有构造函数私有类似于将类This声明为 final - 因此无法扩展。



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



当我尝试用

类来扩展这个类时

  public class这扩展了{
...
}

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



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

  (){..} 
...
}

'm gets:
隐含的超级构造函数this()对于默认构造函数是不可见的
必须显式地调用另一个构造函数



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



如果是,

如果没有,阻止一个类被扩展为
i。)之间的区别使其构造函数为private,
ii。)定义为最后?我看到在一些其他讨论中,Java中的构造函数可以是私有的吗?

具有私有构造函数的类不能在同一类中实例化,这使它无用(可能,但不会编译)从antoher类扩展。



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


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

Eg.:

public class This {
    private This () { }

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

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

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 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 time i'm getting : "Implicit super constructor This() is not visible for default constructor. Must explicitly invoke another constructor."

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

if yes, how?

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

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和更多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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