1013打卡-动手动脑

发布时间 2023-10-13 21:04:20作者: aallofitisst

在 Java 中,字段的访问是基于对象的实际类型,而方法的调用是基于引用类型。当执行 parent.myValue++ 操作时,它会增加 Parent 类的 myValue 字段,因为 myValue 字段是在 Parent 类中声明的。

然而,当调用 parent.printValue() 时,它会调用 Child 类中的 printValue 方法,因为 parent 引用变量引用的是 Child 对象。在 Child 类的 printValue 方法中,它输出的是 Child 类的 myValue 字段,而此时已经执行了 parent.myValue++,所以 Child 类的 myValue 值是1。
所以第四次打印结果是0,而第五次当改变了对象实际类型后则会改变child.myValue的值所以打印结果是1

public class Main {
    public static void main(String[] args) {
        Parent parent=new Parent();
        parent.printValue();
        Child child=new Child();
        child.printValue();
        parent=child;
        parent.printValue();
        parent.myValue++;
        parent.printValue();
        ((Child)parent).myValue++;
        parent.printValue();

    }
}

class Parent{
    public int myValue;
    void printValue(){
        System.out.println(myValue);
    }
}

class Child extends Parent{
    public int myValue;
    void printValue(){
        System.out.println(myValue);
    }
}