我是Java的新手。我想知道在私有类中使用public构造函数有什么用处。在类中的私有类可以从同一类中初始化,那么将私有类的构造函数设为公共的有什么用处呢?
public class MainActivity extends Activity {
private class AcceptThread extends Thread {
public AcceptThread() {
}
}
}
我是Java的新手。我想知道在私有类中使用public构造函数有什么用处。在类中的私有类可以从同一类中初始化,那么将私有类的构造函数设为公共的有什么用处呢?
public class MainActivity extends Activity {
private class AcceptThread extends Thread {
public AcceptThread() {
}
}
}
对于私有类,公共或受保护修饰符似乎没有任何真正的用例。但如果您在单个文件中有多个类(但不是嵌套或本地类),则需要非私有构造函数来实例化私有类。
// X.java
public class X {
private Y y = new Y();
}
class Y {
Y () {
// if this were private, X wouldn't be able to create an instance of Y
}
}
受保护的
可见性就足以创建一个实例。所有非私有修饰符都允许您从同一包中的其他类创建实例,但实际上具有相同的可见性。
公共
方法在这里没有用处。受保护的
也没有用处。IllegalAccessException
。它首先检查类的可见性,然后检查成员的可见性。默认修饰符是最限制性的修饰符,允许您直接从其他类调用构造函数,因此包级私有似乎是构造函数和任何其他非私有方法最适合的可见性。这也具有一个优点,即如果将来更改类的可见性,则不会意外地将构造函数或任何方法暴露给公众。
Y()
函数设为私有函数会更清晰、更整洁。 - assyliasSerialisation: When unmarshalling an object whose superclass is not serializable, the superclass needs a no-arg constructor accessible from the subclass. So, protected
should always suffice here.
Reflective tools: Code that uses reflection to get the inner class constructor through a returned instance. Fails because the type visibility is checked first, as @kapep pointed out, though it leaves a rather interesting error message:
Exception in thread "main" java.lang.IllegalAccessException: Class A can not access a member of class contrived.B$C with modifiers "public"
Inner class extension shenanigans: Don't try this at home:
package a;
class Outer {
private class Inner {
}
}
package b;
// compile error: Outer.Inner has private access in Outer
class Extender extends a.Outer.Inner {
Extender(a.Outer outer) {
outer.super();
}
}
Seemed promising at first, but I didn't get too far with that one.
最终,我找不到一种使私有内部类上的公共构造函数有用的方法。
那么为什么尽管没有任何用途,这在技术上是合法的呢?可能是因为当没有提供其他构造函数时,编译器会自动插入一个无参的公共构造函数。因此,语言不应该禁止这些构造。虽然更像是一种产物而不是原因。