有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java实例方法覆盖与字段隐藏

下面是代码

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 T3true,如果this指向类型为T3的对象

那么,实地访问遵循的规则背后的原理是什么?例如,规则方法对我来说是有意义的

注意:对我来说,记住这些规则是一项开销,除非有正当理由


共 (1) 个答案

  1. # 1 楼答案

    实例方法通过V-table解析,这就是运行时类型的方法被调用的方式。没有这样的表为字段(或静态方法)启用此功能,因此使用编译时类型

    隐藏字段然后做这种事情是非常不寻常的,我会避免它,因为我认为它不可读

    而且java docs确认:

    Within a class, a field that has the same name as a field in the superclass hides the superclass's field, even if their types are different. Within the subclass, the field in the superclass cannot be referenced by its simple name. Instead, the field must be accessed through super, which is covered in the next section. Generally speaking, we don't recommend hiding fields as it makes code difficult to read.

    (我的)

    因此,它应该在你要记住的规则列表中处于较低的位置

    您可以在所有好的IDE中为此打开一个错误/警告,以下是IntelliJ:

    IntelliJ inspection