Home > Software design >  Redefine methods so that they perform the action in the parent version
Redefine methods so that they perform the action in the parent version

Time:12-03

The task is to write an implementation of the smart robot class, which inherits from the regular robot class. The main problem: no other classes in "robot" can be changed, even slightly. It is necessary to redefine the robot's methods so that they both perform an action in the parent version (change coordinates), and simultaneously count the number of steps.

public class Main {

    public static void main(String[] args) {
        SmartRobot robot = new SmartRobot();
        robot.moveDown();
        robot.moveDown();
        robot.moveLeft();
        robot.moveUp();
        robot.moveDown();
        robot.moveLeft();
        robot.moveLeft();

        System.out.println("Координаты робота: "   robot.getX()   ":"   robot.getY());
        System.out.println("Количество шагов: "   robot.getStepsCount());
    }
}

class Robot {
    private int x;
    private int y;

    public void moveRight() {
        x  ;
    }

    public void moveLeft() {
        x--;
    }

    public void moveUp() {
        y--;
    }

    public void moveDown() {
        y  ;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }
}

class SmartRobot extends Robot {

    @Override
    public void moveRight() {
        super.moveRight();
    }

    @Override
    public void moveLeft() {
        super.moveLeft();
    }

    @Override
    public void moveUp() {
        super.moveUp();
    }

    @Override
    public void moveDown() {
        super.moveDown();
    }

    @Override
    public int getX() {
        return super.getX();
    }

    @Override
    public int getY() {
        return super.getY();
    }

    public int getStepsCount() {
        return getX()   getY();
    }
}

CodePudding user response:

X and Y are not the number of your steps. Especially there are minus move such as moveUp and moveLeft.

You can add a member as step counter in SmartRobot, and then make it plus 1 in each moves.

  • Related