Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
public class Main {
public static void main(String[] args) {
Machine r = new Robot();
r.start();
r.stop();
System.out.println("end");
}
}
interface Machine { void start(); void stop(); }
class Robot implements Machine {
public void start() { System.out.print("go "); }
}It does not compile
- Expecting
go end: Java adds no empty method, so a class that implements an interface must write each of its methods, or the program does not compile. - Expecting an error only when
stopis called: the compiler checks the whole class first, so the program never starts and prints nothing.
- How can a class leave an interface method for its subclasses to write?
- Why must the method that implements
startbe declaredpublic?