Multiple Interfaces

Lab Java Intermediate 20 points

Create interfaces Flyer (fly()) and Swimmer (swim()). Duck implements both, Fish only Swimmer, Plane only Flyer. Read names and print what each can do, e.g. Duck: fly swim.

Input

n, then n names.

Output

n lines.

Example

Input

3
Duck
Fish
Plane

Output

Duck: fly swim
Fish: swim
Plane: fly
Sample input available Sample output available
Editor
Java

Hints

A class can implement several interfaces, separated by commas.

Solution explanation

Java has single inheritance of classes but multiple inheritance of interfaces.

Show solution
import java.util.Scanner;

interface Flyer {
    String fly();
}

interface Swimmer {
    String swim();
}

class Duck implements Flyer, Swimmer {
    public String fly() { return "fly"; }
    public String swim() { return "swim"; }
}

class Fish implements Swimmer {
    public String swim() { return "swim"; }
}

class Plane implements Flyer {
    public String fly() { return "fly"; }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            String name = sc.next();
            Object thing = name.equals("Duck") ? new Duck() : name.equals("Fish") ? new Fish() : new Plane();
            StringBuilder sb = new StringBuilder(name + ":");
            if (thing instanceof Flyer) {
                sb.append(' ').append(((Flyer) thing).fly());
            }
            if (thing instanceof Swimmer) {
                sb.append(' ').append(((Swimmer) thing).swim());
            }
            System.out.println(sb);
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD