我可以在 Java 中将受保护的成员公开吗?我想从子类访问它
我是 Java 和 OOP 的新手,
我在类 A 中使用了私有子类(实际上是一个结构体)B,一切都很顺利,直到我决定为子类 B 创建一个父类 C。我想公开一些C 类的受保护成员。
例如:
public class A {
private class B extends C {
public int product;
public int x;
public int y;
public void add() {
product=x+y;
}
}
B b=new B;
b.x=1;
b.y=2;
b.multiply();
System.out.println(b.product+"="+b.x+"x"+b.y);
public class C {
protected int x;
protected int y;
public int sum;
public C(px,py) {
x=px;
y=py;
}
public void sum() {
sum=x+y;
}
}
我得到
默认构造函数的隐式超级构造函数 C() 未定义。 必须定义显式构造函数
当然,我可以删除扩展C,然后回到之前的状态。或者我可以制作一个 getter/setter。但我认为内部结构是可以接受的,并且它应该能够扩展其他类,这是可以理解的。
I'm new to Java and OOP,
I was using a private subclass (actually a struct) B in a class A, and everything went well until I decided to make a parent class C for subclass B. I want make public some of the protected members of class C.
For example:
public class A {
private class B extends C {
public int product;
public int x;
public int y;
public void add() {
product=x+y;
}
}
B b=new B;
b.x=1;
b.y=2;
b.multiply();
System.out.println(b.product+"="+b.x+"x"+b.y);
public class C {
protected int x;
protected int y;
public int sum;
public C(px,py) {
x=px;
y=py;
}
public void sum() {
sum=x+y;
}
}
And I get
Implicit super constructor C() is undefined for default constructor.
Must define an explicit constructor
Of course, I could remove extends C, and go back to what I had before. Or I could make a getter/setter. But I think it is understandable that an inner struct is acceptable, and it should be able to extend other classes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器消息相当清晰 - 在 B 中,您有效地得到:
但失败是因为 C 中没有可调用的无参数构造函数。要么引入无参数构造函数,要么在 B 中提供显式构造函数,该构造函数使用适当的参数调用 C 中的构造函数。
请注意,我不确定拥有所有这些非私有字段是个好主意 - B 中的字段隐藏 C 中的字段也不是一个好主意。您真的想要一个实例吗B 有两个
x
字段和两个y
字段?您意识到它们将是不同的领域,不是吗?如果您只是想有效地提供公共访问,您可以:(
对于
y
也是如此)并从 B 中删除额外的字段。尽管如此,您无法更改 C 中字段的实际可访问性。The compiler message is reasonably clear - in B you've effectively got:
and that fails because there's no parameterless constructor in C to call. Either introduce a parameterless constructor, or provide an explicit constructor in B which calls the constructor in C with appropriate arguments.
I'm not sure it's a good idea to have all these non-private fields, mind you - nor is it a good idea for fields in B to hide fields in C. Do you really want an instance of B to have two
x
fields and twoy
fields? You realise they will be separate fields, don't you?If you just want to effectively provide public access, you could have:
(and the same for
y
) and remove the extra fields from B. You can't change the actual accessibility of the fields in C though.好吧,我正在摆弄自己的代码,发现问题是我需要一个超类 C 的受保护的默认构造函数。它现在可以工作了......
Okay, I was fuddling with my own code and found that the problem is I needed a protected default constructor for superclass C. It works now...