是否可以更改java中继承类的受保护变量?
前任:
class A {
protected Integer x;
class A () {
x = new Integer(0);
}
public setX(Integer m) {
x = m;
}
}
class B extends A {
public class B () {
super();
}
public static void main () {
B b = new B();
b.setX(69);
System.out.println("Value of x is: " + b.x); // expect to be 69. Is it correct?
}
}
Ex:
class A {
protected Integer x;
class A () {
x = new Integer(0);
}
public setX(Integer m) {
x = m;
}
}
class B extends A {
public class B () {
super();
}
public static void main () {
B b = new B();
b.setX(69);
System.out.println("Value of x is: " + b.x); // expect to be 69. Is it correct?
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这就是
受保护
的目的:)Yes, this is what is
protected
for:)受保护的访问意味着成员(或方法)在同一包和类层次结构中可见。
所以是的,您的代码确实达到了预期的结果。
Protected access means that the member (or method) is visible from within the same package and within the class hierarchy.
So yes, your code does have the expected result.
将受保护变量与继承一起使用并不被认为是一个好习惯。
执行此操作的正确方法(不违反封装)是对变量使用私有访问器以及公共(或受保护)getter 和 setter。
It's not considered a good practice to use protected variables with inheritance.
The right way to do this (without violating encapsulation) is using private accesors for the variables and public (or protected) getters and setters.