在 Java 中,字段(Field,成员变量)是可以被继承的,但有一些细节需要注意:
private 的字段
publicprotectedprivate 字段不会被继承(不能直接访问)class Parent {
public int a = 1;
protected int b = 2;
int c = 3;
private int d = 4;
}
class Child extends Parent {
void test() {
System.out.println(a); // ✅
System.out.println(b); // ✅
System.out.println(c); // ✅(同包)
// System.out.println(d); // ❌ 编译错误
}
}
⚠️ Java 中字段不存在多态 / 重写
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
}
调用时:
Parent p = new Child();
System.out.println(p.x); // 输出 10
p.x 取决于 引用类型(Parent)子类定义与父类同名字段时:
class Child extends Parent {
int x = 20;
void test() {
System.out.println(x); // 20
System.out.println(super.x); // 10
}
}
private 字段如何被“间接继承”虽然不能直接访问,但可以通过父类方法访问:
class Parent {
private int d = 4;
public int getD() {
return d;
}
}
| 问题 | 结论 |
|---|---|
| 字段可继承吗 | ✅ 可以(非 private) |
| 字段可重写吗 | ❌ 不可以 |
| 字段有多态吗 | ❌ 没有 |
| private 字段 | ❌ 不继承,但可通过方法访问 |
如果你是想问 反射中的 Field 是否可继承,或者 Spring / JPA 字段继承,我也可以继续讲。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。