Description:
In this lab we are given a movable interface code, which we then must use to make an output as shown in the screenshot. We must use this code to create an interface for three classes; a car, a plane, and a ship. The interface will be a polymorphic because it will have the same structure and process, but it will output different message for each class.
Code:
package lab6; public class MovableStep { public static void main(String[] args) { Movable[] myMovables = new Movable[3]; myMovables[0] = new Plane(); myMovables[1] = new Car(); myMovables[2] = new Ship(); for (Movable v: myMovables){ v.moveForward(); v.moveBackward(); v.stop(); v.moveLeft(); v.moveRight(); System.out.println("---------------------"); } } }
Interface Given code
package lab6; public interface Movable { public void moveForward(); public void moveBackward(); public void stop(); public void moveLeft(); public void moveRight(); }
Plane
package lab6; public class Plane implements Movable { public void moveForward() { System.out.println("Plane flying forward"); } public void moveBackward() { System.out.println("Plane taxiing backward"); } public void stop() { System.out.println("Plane landed"); } public void moveLeft() { System.out.println("Plane flying left"); } public void moveRight() { System.out.println("Plane flying right"); } }
Car
package lab6; public class Car implements Movable { public void moveForward() { System.out.println("Car drives forward"); } public void moveBackward() { System.out.println("Car drives backward"); } public void stop() { System.out.println("Car parked"); } public void moveLeft() { System.out.println("Car drives left"); } public void moveRight() { System.out.println("Car drives right"); } }
Ship
package lab6; public class Ship implements Movable { public void moveForward() { System.out.println("Ship navigates forward"); } public void moveBackward() { System.out.println("Ship navigates backward"); } public void stop() { System.out.println("Ship docked"); } public void moveLeft() { System.out.println("Ship navigates left"); } public void moveRight() { System.out.println("Ship navigates right"); } }
Screenshot: