Lab Description
This lab experiment will be based on the Movable interface which student will create three classes: Car(), Plane(), and Ship() that implements it. These three classes will implement from Movable with the given interface Movable():
public interface Movable {
public void moveForward();
public void moveBackward();
public void stop();
public void moveLeft();
public void moveRight();
}
We will create a program that will polymorphically process an array of movable which will call each of the interface methods. The object of each one of the classes will be created and implemented so the compiled and processed result should output as following:
Plane flying forward
Plane taxiing backward
Plane landed
Plane flying left
Plane flying right
———————
Car drives forward
Car drives backward
Car parked
Car turns left
Car turns right
———————
Ship navigates forward
Ship navigates backward
Ship docked
Ship navigates left
Ship navigates right
———————
Program Codes
package lab4; public class Movables { public static void main(String[] args) { Movable[] myMovable = new Movable[3]; myMovable[0] = new Plane(); myMovable[1] = new Car(); myMovable[2] = new Ship(); for (Movable m: myMovable){ m.moveForward(); m.moveBackward(); m.stop(); m.moveLeft(); m.moveRight(); System.out.println("-------------------------"); } } }
package lab4; public interface Movable { public void moveForward(); public void moveBackward(); public void stop(); public void moveLeft(); public void moveRight(); }
package lab4; public class Plane implements Movable{ @Override public void moveForward() { System.out.println("Plane flying forward"); } @Override public void moveBackward() { System.out.println("Plane taxiing backward"); } @Override public void stop() { System.out.println("Plane landed"); } @Override public void moveLeft() { System.out.println("Plane flying left"); } @Override public void moveRight() { System.out.println("Plane flying right"); } }
package lab4; public class Car implements Movable { @Override public void moveForward() { System.out.println("Car drives forward"); } @Override public void moveBackward() { System.out.println("Car drives backward"); } @Override public void stop() { System.out.println("Car parked"); } @Override public void moveLeft() { System.out.println("Car turns left"); } @Override public void moveRight() { System.out.println("Car turn right"); } }
package lab4; public class Ship implements Movable { @Override public void moveForward() { System.out.println("Ship navigates forward"); } @Override public void moveBackward() { System.out.println("Ship navigates backward"); } @Override public void stop() { System.out.println("Ship docked"); } @Override public void moveLeft() { System.out.println("Ship navigates left"); } @Override public void moveRight() { System.out.println("Ship navigates right"); } }