下面是代码,
package ClassesOverridingHidingAccess;
interface I{
int x = 0;
}
class T1 implements I{
int x = 1;
String s(){
return "1";
}
}
class T2 extends T1{
int x = 2;
String s(){
return "2";
}
}
class T3 extends T2{
int x = 3;
String s(){
return "3";
}
void test(){
// Accessing instanc method
System.out.println("s()=\t\t" + s()); // 3
System.out.println("super.s()=\t" + super.s()); // 2
System.out.println("((T2)this).s()= " + ((T2)this).s()); // 3; method is resolved at runtime
System.out.println("((T1)this).s()= " + ((T1)this).s()); // 3; method is resolved at runtime
//Accessing instance attribute
System.out.println("\n\nx=\t\t" + x); // 3
System.out.println("super.x=\t" + super.x); // 2
System.out.println("((T2)this).x=\t" + ((T2)this).x); // 2; resolved at compile time
System.out.println("((T1)this).x=\t" + ((T1)this).x); // 1; resolved at compile time
System.out.println("((I)this).x=\t" + ((I)this).x); // 0; resolved at compile time
}
}
public class SuperAndInstanceMethods {
public static void main(String[] args) {
(new T3()).test();
}
}
在哪里,
它是运行时类,在实例方法访问的情况下很重要。
它是对象的视图,在字段访问的情况下很重要。
强制转换不会改变对象的类类型。我的意思((T1)this) instanceof T3
是true
,如果this
指向对象类型T3
。
那么,字段访问遵循的规则背后的基本原理是什么?规则例如方法对我来说很有意义。
注意:对我来说,除非有正当理由,否则记住这些规则是一种开销。