class 的方法未给出预期结果

Method of a class not giving expected result

我写了以下3段代码:

Driver.java:

package herds;

public class Driver {
    public static void main(String [] args) {
        organism Wolf = new organism(1,2);
        System.out.println(Wolf.toString());
        Wolf.move(1,2);
        System.out.println(Wolf.toString());
        
        dog Bobby = new dog(0,3,"Bobby");
        System.out.println(Bobby.bark());
        System.out.println(Bobby.toString());
        Bobby.move(0, 1);
        System.out.println(Bobby.toString());
    }
}

organism.java

package herds;

public class organism {
    int x; 
    int y;
    
    public organism(int x, int y) {
        this.x = x;
        this.y = y;
    }
    
    public String toString() {
        return "x: " + this.x + ";" + "y: " + this.y;           
    }

    public void move(int dx, int dy) {
        this.x = this.x + dx;
        this.y = this.y + dy;
    }
}

dog.java:

package herds;

public class dog extends organism {
    int x; 
    int y;
    String name;
    
    public dog(int x, int y, String name) {
        super(x, y);
        this.name = name;
    }
    
    public String bark() {
        return this.name +  " says Woof";
    }
    
    @Override
    public void move(int dx, int dy) {
        this.x = dx;
        this.y = dy;
    }
}

我遇到的问题是驱动程序文件的输出。具体来说,它给出以下输出:

x: 1;y: 2
x: 2;y: 4
Bobby says Woof
x: 0;y: 3
x: 0;y: 3

我不明白为什么最后一行是 x: 0;y: 3,而不是 x: 0;y: 1,因为根据狗的移动方法的定义 class,this.x = 0this.y = 1。那么为什么调用这个方法后会出现x: 0y: 3呢?

  1. 您在 class dog.

    中隐藏了 xy
  2. 当您在 move 方法中更新它们时,您会在 dog class.

    中更新它们
  3. 但是 toString 方法从 organism class.

    打印

修复:

只需从 dog class 中删除 xy。您可能需要将 protected 添加到他们在 organism class 中的定义中。 (还要从 dog class 中的 move 中删除 this。说真的,我不喜欢总是将 this 添加到实例变量的风格。)

public class dog extends organism {
    //int x; 
    //int y;
    String name;