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

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

问题描述

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



例如:

  public class This {
私人这个(){}

public someMethod(){
// something here
}
//一些更多 - 没有其他构造函数
}

从我所知道的,使所有构造函数私有化类似于将类This声明为 final - 所以不能扩展。



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



当我尝试用类似

  public class扩展此{
...
}

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



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

  public class扩展这个{
(){...}
...
}

这次我'm get:
隐式超级构造函数这个()对于默认构造函数是不可见的
必须显式调用另一个构造函数。



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



如果是,怎么样?



如果没有,停止一个类被扩展
之间的区别是什么)
ii。)将其定义为 final



注意:我看到<一些其他的讨论中,一个href =https://stackoverflow.com/questions/2816123/can-a-constructor-in-java-be-private> 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天全站免登陆