Interfaces in Java: Definition, implements and Examples - Quiz
Total: 7 questions
1. What is an interface in Java and how do you create one?
What is an interface in Java and how do you create one?
An interface in Java is a reference type that defines a contract: which methods a class must provide, without describing how they work. An interface is declared with the interface keyword instead of class; a public interface goes into a file with the same name (Moveable.java). Abstract methods are written without a body, just a signature and a semicolon, and interface variables are public static final constants.
public interface Moveable {
int RIGHT = 1; // public static final
void moveRight(); // public abstract
void moveLeft();
}
You cannot create an instance of an interface: new Moveable() is a compile error. But an interface can be used as a variable type: Moveable m = new Transport();. Through such a variable only the methods declared in the interface are available, even if the Transport class has other methods.
2. What does implements mean in Java, and what are the rules for implementing an interface?
What does implements mean in Java, and what are the rules for implementing an interface?
The implements keyword means that a class implements an interface. The rules:
- the class must override all abstract methods of the interface (and of its parent interfaces);
- the implementing method must be
public: you cannot reduce visibility when overriding, otherwise you get the error "attempting to assign weaker access privileges"; @Overrideis optional but lets the compiler check the signature;defaultmethods do not have to be overridden;- if not all abstract methods are implemented, the class must be
abstract.
A class can implement several interfaces separated by commas and extend one class at the same time. The order is fixed: extends first, then implements. The extends keyword means inheritance: a class extends one class, and an interface extends one or more interfaces.
public class ElectricCar extends Car implements Moveable, Chargeable {
// implementations of Moveable and Chargeable methods
}
3. What can an interface contain in Java, and which modifiers do its members have implicitly?
What can an interface contain in Java, and which modifiers do its members have implicitly?
- Constants are implicitly
public static final: the value is set at declaration and cannot be changed (Moveable.RIGHT = 5;does not compile). - Abstract methods are implicitly
public abstract, without a body. - Nested classes and interfaces are implicitly
public static. defaultmethods (Java 8) arepublicand have a body.staticmethods (Java 8) arepublicby default and have a body.privateandprivate staticmethods (Java 9) have a body and hold code shared inside the interface.
Instance fields and constructors are not allowed in an interface. Therefore a field cannot be protected, private or transient, and an abstract method cannot be final, protected or private. Writing public static final and public abstract is optional.
4. What are default and static interface methods in Java 8?
What are default and static interface methods in Java 8?
A default method (default) is an interface method with an implementation. Classes that implement the interface do not have to override it, but they can if the default implementation does not fit. The main reason for default methods is API evolution: this is how stream() and forEach() were added to Collection without breaking existing implementations.
A static interface method (static) also has a body and is called without an object, only through the interface name, for example List.of(). It is not inherited: calling it through an object or through the name of an implementing class is a compile error.
public interface MyIf {
int getNumber();
default String describe() {
return "Number: " + getNumber();
}
static int staticMethod() {
return 0;
}
}
// call: MyIf.staticMethod();
5. What happens if a class implements two interfaces with the same default method?
What happens if a class implements two interfaces with the same default method?
The compiler cannot choose an implementation and reports an error until the class overrides the method itself. Inside the override you can call the implementation of a specific interface with the InterfaceName.super.method() syntax:
public class Smartphone implements Camera, Phone {
@Override
public String info() {
return Phone.super.info() + " with feature: " + Camera.super.info();
}
}
Conflict resolution rules: a class method (including one inherited from a superclass) wins over an interface default method; a more specific sub-interface wins over its parent; in all other cases the programmer must resolve the conflict.
6. What are functional and marker interfaces in Java?
What are functional and marker interfaces in Java?
A functional interface is an interface with exactly one abstract method (default and static methods do not count). It can be implemented with a lambda expression or a method reference. The @FunctionalInterface annotation is optional, but it makes the compiler check that there is exactly one abstract method. JDK examples: Runnable, Comparator, Function, Predicate.
@FunctionalInterface
public interface Calculator {
int apply(int a, int b);
}
Calculator sum = (a, b) -> a + b;
A marker interface is an interface with no methods and no constants. By implementing it, a class "marks" itself, and the JVM or libraries check the mark with instanceof. Examples: Serializable and Cloneable. Cloneable does not declare clone(); it only allows Object.clone() to create a copy instead of throwing CloneNotSupportedException. In modern code annotations are often used instead of marker interfaces.
7. What is the difference between an interface and an abstract class in Java?
What is the difference between an interface and an abstract class in Java?
The main differences:
- A class can extend (
extends) only one class, but implement (implements) any number of interfaces. An interface can extend several interfaces at once:interface Football extends Sport, TVProgram. - An abstract class can have instance fields and constructors; an interface has only
public static finalconstants and no constructors. - Abstract interface methods are always
public; in an abstract class they can also beprotectedor package-private.
An abstract class is chosen for shared state and code of related classes, an interface for describing a capability (a contract) that unrelated classes can have. That is why Java supports multiple inheritance of type through interfaces, but not multiple inheritance of state.