Lab 4

Description:  Create an interface Movable, base on that interface, create three classes, car, plane, ship that implement it.  Then create a program that will polymorphically process an array of Movable by calling each interface methods.  The result should be something like:

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
———————

 

Code:

 

Main

public class lab4 {
	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("---------------------");
		}
	}
}

Movable

public interface Movable {
	public void moveForward();
	public void moveBackward();
	public void stop();
	public void moveLeft();
	public void moveRight();
}

Plane

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

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 turns left");
		}

	public void moveRight() {
		System.out.println("Car turn right");
	}
}

Ship

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

l4

Leave a Reply

Your email address will not be published. Required fields are marked *