Java 访问隐藏在第三个扩展类中的间接超类变量
假设我有如下代码:Java 访问隐藏在第三个扩展类中的间接超类变量,java,inheritance,super,Java,Inheritance,Super,假设我有如下代码: class A { int a = 1; } class B extends A { int a = 2; } class C extends B { int a = 3; void print_it() { int a = 4; // Local variable "a" to the " print_it " method System.out.println(a);
class A {
int a = 1;
}
class B extends A {
int a = 2;
}
class C extends B {
int a = 3;
void print_it() {
int a = 4; // Local variable "a" to the " print_it " method
System.out.println(a); //Should be 4
System.out.println(this.a); //Should be 3
System.out.println(super.a); //Should be 2
System.out.println("HOW DO I PRINT \" a \" OF THE \" CLASS A \" "); //I need to print 1
}
public static void main(String[] argue) {
C obj = new C();
obj.print_it();
}
}
如何访问间接继承到“C类”的“a类”的“a”。我知道我可以创建“a类”的对象,我也知道我可以在“B类”中创建一个方法来返回“super.a”(“a类”的“变量”),当然,如果它是静态的,我可以像“a.a”一样访问它
如果有任何其他方法可以直接访问它,请告诉我
(提前感谢)。转换到A,然后访问变量:
((A)this).a
我可能值得一提的是,这只适用于变量,而不适用于方法。