传值和多态

Hel*_*esh 3 java polymorphism inheritance pass-by-value

我对编程很新,并且不理解为什么这段代码打印200而不是206.类Cat中的move方法会覆盖Animal类中的move方法.为什么在第2行的方法调用后,Animals中的'location'实例变量不会更改为206?但是,当我删除类Cat中的方法时,实例变量DOES会更改为206.它背后的逻辑是什么?

public  class Animals {
   int location = 200; //line 1

   public void move(int by) {
       location = location+by;
   }

    public final static void main (String...args) {
        Animals a = new Cat();
        a.move(6); //line 2
        System.out.println(a.location); //200, but should print 206 in my opinion
    }
}

class Cat extends Animals {
    int location = 400;

    @Override
    public void move(int by) { //if this method is removed, a.location prints 206
        location = location+by;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sur*_*tta 8

a.move(6); // line 2
System.out.println(a.location);
Run Code Online (Sandbox Code Playgroud)

在第一行中,您正在执行Cat中的方法,这意味着您正在修改Cat类的变量.

在第二行,您将从中打印变量Animal.

您无法在Java中覆盖变量.只有方法.

而你所做的就是将实例变量location置于阴影上Cat,当你在Cat类中修改它时,你不再指向它Animal了.当您在Cat类中删除该变量时,您指的是AnimalClass.