温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java Field字段可继承吗

发布时间:2026-10-27 13:56:55 来源:亿速云 阅读:94 作者:小樊 栏目:编程语言

在 Java 中,字段(Field,成员变量)是可以被继承的,但有一些细节需要注意:


1️⃣ 字段的继承规则

  • 子类会继承父类中所有非 private 的字段
    • public
    • protected
    • 默认(包访问权限,同包可访问)
  • private 字段不会被继承(不能直接访问)
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); // ❌ 编译错误
    }
}

2️⃣ 字段“不可被重写(override)”

⚠️ 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)
  • 方法才是动态绑定,字段是静态绑定

3️⃣ 隐藏(Field Hiding)

子类定义与父类同名字段时:

  • 称为 字段隐藏
  • 父类字段依然存在,只是被“遮蔽”
class Child extends Parent {
    int x = 20;

    void test() {
        System.out.println(x);      // 20
        System.out.println(super.x); // 10
    }
}

4️⃣ private 字段如何被“间接继承”

虽然不能直接访问,但可以通过父类方法访问:

class Parent {
    private int d = 4;
    public int getD() {
        return d;
    }
}

✅ 总结

问题 结论
字段可继承吗 ✅ 可以(非 private)
字段可重写吗 ❌ 不可以
字段有多态吗 ❌ 没有
private 字段 ❌ 不继承,但可通过方法访问

如果你是想问 反射中的 Field 是否可继承,或者 Spring / JPA 字段继承,我也可以继续讲。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手