简体   繁体   中英

Method of a class not giving expected result

I wrote the following 3 pieces of code:

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;
    }
}

The problem I'm having is with the output of the Driver file. Specifically, it gives the following as output:

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

I don't understand why the final line would be x: 0;y: 3 , and not x: 0;y: 1 , because by the definition of the move method for the dog class, this.x = 0 and this.y = 1 . So why would x: 0 and y: 3 after this method is called?

  1. You are hiding x and y in the class dog .

  2. When you update them in the move method, you update them in the dog class.

  3. But the toString method prints from the organism class.

Fix:

Just remove x and y from the dog class. You may need to add protected to their definition in the organism class. (Also remove the this from move in the dog class. Seriously I don't like the style of always adding this to instance variables.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM