What this topic covers
12 subtopics- Interfaces11
- Python ABCs7
- Pure virtual functions6
- Abstract classes5
- Default method rules3
- Design3
- Functional interfaces3
- Abstract class vs interface2
- Protocols2
- Abstract methods1
- Basics1
- UML1
- Beginner 15
- Intermediate 15
- Advanced 15
About this topic
Abstraction exposes what an object does and hides how. An abstract class can hold state and some implemented methods but cannot be instantiated; an interface is a pure contract that a class promises to fulfil (since Java 8 it may also carry default methods). C++ uses pure virtual functions (= 0), and Python uses abc.ABC with @abstractmethod or structural Protocols. Designs are drawn as UML diagrams, and every program was run.
Free preview
Sample questions
Try each one first, then open the answer for the explanation and why the other options are wrong.
Why does this fail to compile?
abstract class Shape {
abstract double area();
}
public class Main {
public static void main(String[] args) {
Shape s = new Shape();
System.out.println(s.area());
}
}
Show answer and explanation
Explanation
An abstract class is incomplete – area() has no body – so only concrete subclasses can be created. A variable of type Shape is still allowed.
Why the other options are wrong
- AAbstract methods cannot be static.
- BAbstract methods have no body.
- CAbstract classes are valid.
What does this print?
public class Main {
interface Temperature {
double celsius();
static Temperature ofFahrenheit(double f) { return () -> (f - 32) * 5 / 9; }
default boolean freezing() { return celsius() <= 0; }
}
public static void main(String[] args) {
Temperature t = Temperature.ofFahrenheit(212);
System.out.println(t.celsius() + " " + t.freezing() + " " + Temperature.ofFahrenheit(14).freezing());
}
}
Show answer and explanation
Explanation
Static interface methods (Java 8) belong to the interface and are called through its name – handy factories such as List.of. 212°F = 100°C; 14°F = −10°C.
Why the other options are wrong
- BThe factory converts to Celsius.
- CStatic methods are allowed.
- D100°C is not freezing.
A superclass method and an interface default method have the same signature. What does this print?
public class Main {
interface Named { default String name() { return "interface"; } }
static class Base { public String name() { return "class"; } }
static class Thing extends Base implements Named { }
public static void main(String[] args) {
Named n = new Thing();
System.out.println(n.name());
}
}
Show answer and explanation
Explanation
Rule 1: "class wins" – a method from the superclass chain beats any interface default. Rule 2: a more specific interface beats a less specific one. Rule 3: otherwise the class must override.
Why the other options are wrong
- AThe class method resolves it.
- BSuperclass methods take priority over defaults.
- COnly one method runs.