如何从子类访问Java中超类的受保护字段? [英] How to access protected field of a super class in java from subclasses?

查看:61
本文介绍了如何从子类访问Java中超类的受保护字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Java的子类访问父类的受保护字段:

I want to access a protected field of a super-class from a sub-class in Java:

Class Super {
 protected int field; // field set to a value when calling constructor
}
Class B extends Super { // field of super class is set to value when calling
                        // constructor

}

Class C extends Super { // same here

}
B b = new B();
C c = new C();
b.super.field ?

推荐答案

该类可以直接访问该字段,就好像它是自己的字段一样.需要注意的是,进行访问的代码必须在派生类本身的代码中,而不是在使用派生类的代码中:

The class can access the field directly, as if it were its own field. The catch is that the code doing the access must be in the code of the derived class itself, not in the code using the derived class:

class B extends Super {
    ...
    int getSuperField() {
        return field;
    }
}

这篇关于如何从子类访问Java中超类的受保护字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆