Lab 4 Interface
Interface
Lab 4 procedures:
You are give the following interface Movable():
public interface Movable { public void moveForward(); public void moveBackward(); public void stop(); public void moveLeft(); public void moveRight(); }
Base on the Movable interface create three classes: Car(), Plane(), and Ship() that implement it. After that, create a program that will polymorphically process an array of Movable by calling each of the interface methods, after creating an object for each one of the classes. Implement the classes in such a way that the output is:
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 ---------------------
Overview:
In this lab we were give a Interfaces in which we added appropriate so we can display the message that was wanted by the client.
Code:
Main class
package Lab4; public class Lab4 { public static void main(String[] args) { Movable[] actions = new Movable[3]; actions[0] = new Plane(); actions[1] = new Car(); actions[2] = new Ship(); for (Movable movable : actions) { movable.moveFoward(); movable.moveFoward(); movable.stop(); movable.moveLeft(); movable.moveRight(); System.out.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*"); } } }
Movable
package Lab4; public interface Movable { void moveFoward(); void moveBackward(); void stop(); void moveLeft(); void moveRight(); }
Plane class
package Lab4; public class Plane implements Movable { @Override public void moveFoward() { 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"); } }
Car Class
package Lab4; public class Car implements Movable { @Override public void moveFoward() { System.out.println("Car drives foward"); } @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 turns right"); } }
Ship Class
package Lab4; public class Ship implements Movable { @Override public void moveFoward() { 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"); } }
Leave a Reply