Interfaces
Completed
Create an interface Greeter with String greet(String name), and implementations English (Hello, NAME), Spanish (Hola, NAME) and Pirate (Ahoy, NAME!). Read a language and names and greet each.
Input
Line 1: en, es or pirate. Line 2: n. Then n names.
Output
n greetings.
Example
Input
pirate 2 Jack Anne
Output
Ahoy, Jack! Ahoy, Anne!
Editor
Java
Hints
A class implements an interface by providing all its methods.
Interface methods are public, so implementations must be public.
Solution explanation
Code written against an interface works with any implementation - choose one at runtime.
Show solution
import java.util.Scanner;
interface Greeter {
String greet(String name);
}
class English implements Greeter {
public String greet(String name) {
return "Hello, " + name;
}
}
class Spanish implements Greeter {
public String greet(String name) {
return "Hola, " + name;
}
}
class Pirate implements Greeter {
public String greet(String name) {
return "Ahoy, " + name + "!";
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String lang = sc.next();
Greeter g = lang.equals("es") ? new Spanish() : lang.equals("pirate") ? new Pirate() : new English();
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println(g.greet(sc.next()));
}
}
}