我试过这个:
class protectedfinal
{
static abstract class A
{
protected final Object a;
}
static class B extends A
{
{ a = new Integer(42); }
}
public static void main (String[] args)
{
B b = new B();
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到了这个错误:
protectedfinal.java:12: error: cannot assign a value to final variable a
{ a = new Integer(42); }
^
1 error
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
有些人建议使用构造函数,但这只适用于某些情况.它适用于大多数对象,但不能从构造函数中引用对象本身.
static abstract class X
{
protected final Object x;
X (Object x) { this.x = x; } …Run Code Online (Sandbox Code Playgroud) java ×1