Interfaces — Fundamentals
Interface basics, multiple inheritance, abstract vs interface
- Understand what interfaces are and why they exist
- Implement interfaces and achieve multiple inheritance
- Differentiate between abstract classes and interfaces
Part of the Concept and Coding Java lecture series. These notes are fully self-contained — no prior lecture viewing is required. This chapter covers interfaces in depth: definition, why they exist, methods, fields, implementation rules, nested interfaces, and the full comparison with abstract classes. Java 8 and Java 9 interface features are covered in Part 2.
Table of Contents
- Methods in an Interface
- Fields in an Interface
- Interface Implementation
- Abstract Class Implementing an Interface
- Nested Interfaces
- Interface vs Abstract Class — 10 Differences
- Mermaid Diagrams
- Quick-Reference Tables
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Cheat Sheet
1. What is an Interface?
Overview
An interface is one of the most fundamental concepts in Java. It is the backbone of abstraction, polymorphism, and loosely coupled design. Every professional Java codebase uses interfaces extensively.
Real-World Analogy
Consider driving a car. When you press the brake pedal, the car slows down. You (System 1) interact with the car (System 2) through the pedal — which is the interface. You don't know whether the car uses disc brakes, drum brakes, regenerative braking, or ABS logic. All of that is hidden. The pedal is all you need to interact with.
Another analogy: a TV remote control. The remote is the interface between you and the TV's internal electronics. You press "volume up" — you don't care how transistors and capacitors respond inside the TV.
Technical Definition
An interface in Java is a contract that defines what a class must do, without specifying how it will do it. It enables two systems (or classes) to interact with each other without one needing to know the internal details of the other.
In short: an interface defines method signatures (the what) and leaves implementation (the how) entirely to the classes that use it.
One-Line Summary
Interface = 100% abstraction (before Java 8). It defines a contract that implementing classes must fulfill.
2. How to Define an Interface
Syntax
1modifier interface InterfaceName extends ParentInterface1, ParentInterface2 {2 // method signatures (abstract by default)3 // constants (public static final by default)4}Syntax Breakdown
| Part | Explanation |
|---|---|
modifier | Only public or default (package-private) are allowed |
interface | The keyword that declares this as an interface |
InterfaceName | Name of the interface — by convention, a noun or adjective (e.g., Flyable, Comparable) |
extends | Used when this interface extends one or more other interfaces |
ParentInterface1, ParentInterface2 | Comma-separated list of parent interfaces (NOT classes) |
{ ... } | Body — contains method signatures and constants |
Access Modifiers for Interfaces
| Modifier | Allowed? | Meaning |
|---|---|---|
public | ✅ Yes | Accessible from any package |
| (default / package-private) | ✅ Yes | Accessible only within the same package |
protected | ❌ No | Not applicable to top-level interfaces |
private | ❌ No | Not applicable to top-level interfaces |
Basic Example
1public interface Bird {2 void fly(); // abstract method — signature only, no body3}Interface Extending Multiple Interfaces
An interface can extend multiple other interfaces using a comma-separated list:
1public interface Bird {2 void fly();3}4
5public interface LivingThing {6 void breathe();7}8
9// NonFlyingBird extends both Bird and LivingThing10public interface NonFlyingBird extends Bird, LivingThing {11 void run();12}implements for interfaces and extends for classes.3. Why We Need Interfaces
There are three primary reasons Java provides interfaces:
3.1 Abstraction
What is Abstraction?
Abstraction means hiding implementation details and exposing only the features the user needs to know.
How Interfaces Achieve Abstraction
An interface defines only method signatures — there is no implementation code. The implementing class provides the how. The caller only ever sees the what.
1┌─────────────┐ interface ┌─────────────────┐2│ System 1 │ ─── fly(), eat() ──▶ System 2 │3│ (caller) │ │ (implementer) │4│ │ │ full logic here │5└─────────────┘ └─────────────────┘6 ↑7knows nothing about8System 2's internalsCode Example
1public interface Car {2 void applyBrake(); // caller only knows this method exists3}4
5public class Audi implements Car {6 @Override7 public void applyBrake() {8 // hundreds of lines of internal logic:9 // ABS activation, brake fluid pressure, calliper engagement...10 System.out.println("Audi: ABS brake engaged.");11 }12}13
14public class Main {15 public static void main(String[] args) {16 Car car = new Audi();17 car.applyBrake(); // caller doesn't know or care how this works18 }19}Audi: ABS brake engaged.
The Main class only knows about applyBrake(). The entire internal complexity of braking is hidden behind the interface — that is abstraction.
3.2 Polymorphism
Interface as a Data Type
An interface can be used as a reference type (data type), just like a class. This enables polymorphism — one reference variable that can hold objects of different concrete classes, and calls the correct method at runtime.
java
Bird b = new Bird(); // ❌ COMPILE ERROR — cannot instantiate interface
`
But you can hold a reference to a concrete class that implements it:
`java
Bird b = new Eagle(); // ✅ Eagle implements Bird
``Code Example Runtime Polymorphism
1public interface Bird {2 void fly();3}4
5public class Eagle implements Bird {6 @Override7 public void fly() {8 System.out.println("Eagle soars at high altitude.");9 }10}11
12public class Hen implements Bird {13 @Override14 public void fly() {15 System.out.println("Hen flutters a few feet off the ground.");16 }17}18
19public class Main {20 public static void main(String[] args) {21 Bird birdObj1 = new Eagle(); // interface reference → Eagle object22 Bird birdObj2 = new Hen(); // interface reference → Hen object23
24 birdObj1.fly(); // runtime lookup: birdObj1 holds Eagle → calls Eagle.fly()25 birdObj2.fly(); // runtime lookup: birdObj2 holds Hen → calls Hen.fly()26 }27}Eagle soars at high altitude. Hen flutters a few feet off the ground.
How Runtime Dispatch Works
When birdObj1.fly() is called:
- JVM checks: what object does
birdObj1actually hold at runtime? - Answer: an
Eagleobject. - JVM calls
Eagle'sfly()method.
This decision happens at runtime (not compile time) — that is dynamic dispatch / runtime polymorphism.
3.3 Multiple Inheritance & The Diamond Problem
Why Multiple Inheritance is Banned for Classes
In Java, a class cannot extend more than one class. The reason is the Diamond Problem.
The Diamond Problem Explained
Imagine (hypothetically) that multiple class inheritance was allowed:
1 WaterAnimal LandAnimal2 canBreathe() canBreathe()3 \ /4 \ /5 Crocodile6 canBreathe() ???1// HYPOTHETICAL — does NOT compile in Java2class WaterAnimal {3 void canBreathe() { System.out.println("Breathing in water"); }4}5
6class LandAnimal {7 void canBreathe() { System.out.println("Breathing on land"); }8}9
10// This would cause ambiguity:11class Crocodile extends WaterAnimal, LandAnimal { // ❌ not allowed12 // Which canBreathe() should be called?13 // WaterAnimal's or LandAnimal's?14 // The compiler cannot decide — this is the Diamond Problem.15}When crocodileObj.canBreathe() is called, the compiler has no way to determine which parent's implementation to use. This ambiguity is the Diamond Problem, and it is why Java does not allow multiple class inheritance.
How Interfaces Solve This
With interfaces, methods have no implementation (just signatures). So there is nothing to be ambiguous about. The implementing class provides its own implementation, which overrides everything:
1interface WaterAnimal {2 void canBreathe(); // signature only — no implementation3}4
5interface LandAnimal {6 void canBreathe(); // signature only — no implementation7}8
9// ✅ No ambiguity — Crocodile provides ITS OWN implementation10class Crocodile implements WaterAnimal, LandAnimal {11 @Override12 public void canBreathe() {13 System.out.println("Crocodile breathes through nostrils.");14 }15}16
17public class Main {18 public static void main(String[] args) {19 Crocodile c = new Crocodile();20 c.canBreathe(); // no confusion — calls Crocodile's own implementation21 }22}Crocodile breathes through nostrils.
When c.canBreathe() is called, there is zero ambiguity. The compiler calls Crocodile's own canBreathe() — which it was required to provide when it implemented both interfaces.
java
class Crocodile implements WaterAnimal, LandAnimal, Reptile, Predator { ... }
``4. Methods in an Interface
Key Rules for Interface Methods
Rule 1 All Methods Are Implicitly `public`
Whether or not you write public, all methods in an interface are public by default:
1public interface Bird {2 void fly(); // implicitly public — same as writing 'public void fly()'3 public void eat(); // explicitly public — same as above4}Both fly() and eat() are identical in terms of access — both are public. Writing public is optional but not wrong.
Rule 2 Methods Cannot Be Declared `final`
1public interface Bird {2 final void fly(); // ❌ COMPILE ERROR3}Why? The final keyword on a method means it cannot be overridden in subclasses. But the entire purpose of an interface method is to be overridden (implemented) by concrete classes. Declaring it final would contradict the fundamental purpose of an interface. The two concepts are mutually exclusive.
Rule 3 Methods Are Abstract by Default (Pre-Java 8)
All methods in an interface (before Java 8) are implicitly abstract — they have no body, only a signature:
1public interface Bird {2 void fly(); // implicitly: public abstract void fly();3 abstract void eat(); // same as above — 'abstract' is redundant but valid4}default, static, and private methods in interfaces, which CAN have method bodies. These are covered in Part 2 of this series.Summary Table Interface Method Rules
| Property | Rule |
|---|---|
| Access modifier | Implicitly public — always |
| Abstract | Implicitly abstract (pre-Java 8) — no body |
final | ❌ Not allowed — contradicts overriding |
private | ❌ Not allowed before Java 9 |
protected | ❌ Not allowed |
static | ✅ Allowed from Java 8 (with body) |
default | ✅ Allowed from Java 8 (with body) |
5. Fields in an Interface
Key Rule All Fields Are `public static final`
Every variable (field) declared in an interface is implicitly:
public— accessible from anywherestatic— belongs to the interface itself, not to any instancefinal— cannot be changed after assignment (it is a constant)
1public interface Bird {2 int MAX_HEIGHT_IN_FEET = 2000;3 // identical to:4 // public static final int MAX_HEIGHT_IN_FEET = 2000;5}Both declarations above are completely equivalent.
Why Are Interface Fields Always Constants?
Interfaces cannot be instantiated, so instance variables (non-static fields) make no sense. Every field must be associated with the interface itself (hence static) and should not be changeable by implementors (hence final). This ensures the interface provides reliable, unchangeable constants.
Code Example
1public interface GeographicConstants {2 double EARTH_RADIUS_KM = 6371.0; // public static final3 int MAX_ALTITUDE_FEET = 60000; // public static final4 String PLANET_NAME = "Earth"; // public static final5}6
7public class FlightCalculator implements GeographicConstants {8 public void display() {9 System.out.println("Planet: " + PLANET_NAME);10 System.out.println("Earth radius: " + EARTH_RADIUS_KM + " km");11 System.out.println("Max altitude: " + MAX_ALTITUDE_FEET + " feet");12 }13}14
15public class Main {16 public static void main(String[] args) {17 FlightCalculator fc = new FlightCalculator();18 fc.display();19
20 // Access directly via interface name — it's static21 System.out.println(GeographicConstants.EARTH_RADIUS_KM);22 }23}Planet: Earth Earth radius: 6371.0 km Max altitude: 60000 feet 6371.0
java
GeographicConstants.EARTH_RADIUS_KM = 5000.0; // ❌ COMPILE ERROR — field is final
``6. Interface Implementation
The `implements` Keyword
A class uses the implements keyword to adopt an interface:
1class ClassName implements InterfaceName {2 // must provide implementation for all abstract methods3}Rule 1 Overriding Method Cannot Have a More Restrictive Access Modifier
Interface methods are implicitly public. When a class implements an interface method, it must maintain or widen the access — it cannot narrow it (e.g., making it protected or private):
1public interface Bird {2 void fly(); // implicitly public3}4
5public class Eagle implements Bird {6 @Override7 protected void fly() { // ❌ COMPILE ERROR — more restrictive than public8 System.out.println("Eagle flies.");9 }10}Fix:
1public class Eagle implements Bird {2 @Override3 public void fly() { // ✅ must be public (same as interface)4 System.out.println("Eagle flies.");5 }6}public, implementing methods must also be public.Rule 2 A Concrete Class Must Implement ALL Abstract Methods
If a concrete class implements an interface but does not implement every abstract method declared in it, the compiler will throw an error:
1public interface Bird {2 void fly();3 void eat();4 void nest();5}6
7public class Eagle implements Bird {8 @Override9 public void fly() { System.out.println("Flying."); }10
11 @Override12 public void eat() { System.out.println("Eating."); }13
14 // ❌ nest() is not implemented — COMPILE ERROR15 // "Eagle is not abstract and does not override abstract method nest() in Bird"16}Fix — implement all methods:
1public class Eagle implements Bird {2 @Override3 public void fly() { System.out.println("Flying."); }4 @Override5 public void eat() { System.out.println("Eating."); }6 @Override7 public void nest() { System.out.println("Nesting."); }8}Rule 3 A Class Can Implement Multiple Interfaces
1interface Flyable { void fly(); }2interface Swimmable { void swim(); }3interface Runnable { void run(); }4
5// One class, three interfaces ✅6public class Duck implements Flyable, Swimmable, Runnable {7 @Override public void fly() { System.out.println("Duck flies."); }8 @Override public void swim() { System.out.println("Duck swims."); }9 @Override public void run() { System.out.println("Duck runs."); }10}Full Implementation Code Example
1public interface Bird {2 void fly();3 void eat();4}5
6public class Eagle implements Bird {7 @Override8 public void fly() {9 System.out.println("Eagle: soaring at 3000 feet.");10 }11
12 @Override13 public void eat() {14 System.out.println("Eagle: catching fish.");15 }16}17
18public class Hen implements Bird {19 @Override20 public void fly() {21 System.out.println("Hen: fluttering 2 feet.");22 }23
24 @Override25 public void eat() {26 System.out.println("Hen: pecking at grain.");27 }28}29
30public class Main {31 public static void main(String[] args) {32 Bird b1 = new Eagle();33 Bird b2 = new Hen();34
35 b1.fly(); b1.eat();36 b2.fly(); b2.eat();37 }38}Eagle: soaring at 3000 feet. Eagle: catching fish. Hen: fluttering 2 feet. Hen: pecking at grain.
7. Abstract Class Implementing an Interface
Key Rule
An abstract class that implements an interface is not required to implement all abstract methods from that interface. It can:
- Implement some methods (provide concrete implementations).
- Leave others as abstract (to be implemented by a concrete subclass).
- Add additional abstract methods of its own.
A concrete class in the chain, however, must implement every remaining unimplemented abstract method.
Code Example
1public interface Bird {2 void canFly();3 void numberOfLegs();4}5
6// Abstract class implementing Bird — not forced to implement everything7public abstract class Eagle implements Bird {8 @Override9 public void canFly() { // ✅ provides implementation10 System.out.println("Yes, eagle can fly.");11 }12 // numberOfLegs() is NOT implemented — left as abstract for children13
14 public abstract void wingSpan(); // adds a new abstract method15}16
17// Concrete class — MUST implement all remaining abstract methods18public class WhiteEagle extends Eagle {19 @Override20 public void numberOfLegs() { // ✅ from Bird interface21 System.out.println("2 legs.");22 }23
24 @Override25 public void wingSpan() { // ✅ from Eagle abstract class26 System.out.println("Wingspan: 7 feet.");27 }28}29
30public class Main {31 public static void main(String[] args) {32 WhiteEagle we = new WhiteEagle();33 we.canFly(); // from Eagle (concrete)34 we.numberOfLegs(); // from WhiteEagle (overrides Bird's abstract)35 we.wingSpan(); // from WhiteEagle (overrides Eagle's abstract)36 }37}Yes, eagle can fly. 2 legs. Wingspan: 7 feet.
Class Hierarchy Diagram
How the Concrete Class Checks for Unimplemented Methods
When the compiler processes WhiteEagle, it traces up the hierarchy and identifies every unimplemented abstract method:
- From
Eagle(parent):wingSpan()— abstract, not implemented →WhiteEaglemust implement it ✅ - From
Bird(viaEagle):canFly()— already implemented inEagle→ no action needed ✅ - From
Bird(viaEagle):numberOfLegs()— not implemented anywhere →WhiteEaglemust implement it ✅
8. Nested Interfaces
Definition
A nested interface is an interface declared inside another interface or inside a class.
When to Use
Nested interfaces are used to group logically related interfaces in one place — similar to how nested classes group related classes.
Map.Entry inside Map) and occasionally in interview questions.8.1 Interface Nested Within an Interface
Rules
| Rule | Detail |
|---|---|
| Access modifier | Must be public — everything inside an interface is public |
| Can have its own abstract methods | ✅ Yes |
| Can be implemented independently | ✅ Yes |
| Can be implemented alongside the outer interface | ✅ Yes |
Code Example
1public interface Bird {2 void canFly(); // outer interface method3
4 public interface NonFlyingBird { // nested interface — must be public5 void canRun(); // nested interface method6 }7}Usage Implementing Only the Outer Interface
1public class Eagle implements Bird {2 @Override3 public void canFly() {4 System.out.println("Eagle can fly.");5 }6 // NonFlyingBird not implemented — not required7}Usage Implementing Only the Inner (Nested) Interface
1public class Penguin implements Bird.NonFlyingBird { // access via Outer.Inner2 @Override3 public void canRun() {4 System.out.println("Penguin can run fast.");5 }6}7
8public class Main {9 public static void main(String[] args) {10 Bird.NonFlyingBird nfb = new Penguin();11 nfb.canRun();12 }13}Penguin can run fast.
Usage Implementing Both Outer and Inner Interface
1public class Ostrich implements Bird, Bird.NonFlyingBird {2 @Override3 public void canFly() {4 System.out.println("Ostrich cannot really fly.");5 }6
7 @Override8 public void canRun() {9 System.out.println("Ostrich runs at 45 mph.");10 }11}8.2 Interface Nested Within a Class
When an interface is nested inside a class (not another interface), it can have any access modifier: public, protected, private, or default.
Rules
| Property | Nested in Interface | Nested in Class |
|---|---|---|
| Access modifiers allowed | public only | public, protected, private, default |
| Reason | Interface members are always public | Class members can have any access |
Code Example
1public class Bird {2 protected interface NonFlyingBird { // ✅ protected is allowed here3 void canRun();4 }5}6
7public class Emu implements Bird.NonFlyingBird {8 @Override9 public void canRun() {10 System.out.println("Emu runs at 30 mph.");11 }12}13
14public class Main {15 public static void main(String[] args) {16 Bird.NonFlyingBird nfb = new Emu();17 nfb.canRun();18 }19}Emu runs at 30 mph.
Private Nested Interface (Inside a Class)
1public class SecuritySystem {2 private interface Authenticator { // only SecuritySystem can see this3 boolean authenticate(String password);4 }5
6 private class SimpleAuth implements Authenticator {7 @Override8 public boolean authenticate(String password) {9 return "secret123".equals(password);10 }11 }12
13 public boolean login(String password) {14 Authenticator auth = new SimpleAuth();15 return auth.authenticate(password);16 }17}This pattern fully encapsulates the authentication strategy inside SecuritySystem — no outside class even knows Authenticator exists.
8.3 Famous Real-World Example `Map.Entry`
Java's own standard library uses nested interfaces. Map.Entry is an interface nested inside the Map interface:
1// Simplified — how Java's Map.Entry works2public interface Map<K, V> {3 interface Entry<K, V> { // nested interface4 K getKey();5 V getValue();6 }7
8 Set<Entry<K, V>> entrySet();9}You use it like this:
1Map<String, Integer> scores = new HashMap<>();2scores.put("Alice", 95);3
4for (Map.Entry<String, Integer> entry : scores.entrySet()) {5 System.out.println(entry.getKey() + " → " + entry.getValue());6}9. Interface vs Abstract Class 10 Differences
This is one of the most frequently asked topics in Java interviews.
| # | Property | Abstract Class | Interface |
|---|---|---|---|
| 1 | Keyword | abstract class ClassName | interface InterfaceName |
| 2 | Used with | extends (child class) | implements (child class) |
| 3 | Method types | Both abstract AND concrete methods | Only abstract (pre-Java 8); default/static added in Java 8 |
| 4 | Inheritance | Can extend one class + multiple interfaces | Can extend multiple interfaces only |
| 5 | Variables | Can be static, non-static, final, non-final | Always public static final (constants only) |
| 6 | Access modifiers on members | private, protected, public, default | Only public (pre-Java 9); private added in Java 9 |
| 7 | Multiple inheritance | ❌ Not supported | ✅ Supported (a class can implement many) |
| 8 | Constructor | ✅ Can have constructors | ❌ Cannot have constructors |
| 9 | Abstract method declaration | Requires abstract keyword: abstract void fly(); | No keyword needed — signature alone is abstract: void fly(); |
| 10 | Abstract method access | Can be protected, public, or default | Always public |
Code Side-by-Side
1// Abstract Class2abstract class Animal {3 String name; // instance variable ✅4 private int age; // private variable ✅5
6 Animal(String name) { // constructor ✅7 this.name = name;8 }9
10 abstract void makeSound(); // abstract method — needs 'abstract' keyword11 void breathe() { // concrete method ✅12 System.out.println("Breathing.");13 }14}15
16// Interface17interface Creature {18 int MAX_LIFESPAN = 100; // public static final constant19
20 void makeSound(); // abstract — no keyword needed, no body21 // void breathe() { ... } // ❌ not allowed pre-Java 822}Key Notes on the 10 Differences
Difference 3 — Methods (important clarification): Before Java 8, interfaces could ONLY have abstract methods. From Java 8, default and static methods with bodies are allowed. From Java 9, private methods are also allowed. These are covered in Part 2.
Difference 7 — Multiple Inheritance:
1// Abstract class — only ONE parent class2abstract class A extends B { } // B must be a class3
4// Interface — MANY parent interfaces5interface X extends Y, Z, W { } // Y, Z, W must all be interfaces6
7// Class implementing multiple interfaces8class MyClass implements X, Y, Z { } // ✅ allowedDifference 10 — Abstract method in abstract class can be protected:
1abstract class Animal {2 protected abstract void makeSound(); // ✅ protected is fine in abstract class3}4
5// But in interface — always public:6interface Creature {7 void makeSound(); // implicitly public — cannot be protected8}10. Mermaid Diagrams
Interface Implementation Chain
Multiple Interface Implementation (Diamond Problem Solution)
Nested Interface Structure
Abstract Class + Interface Hierarchy
Interface Definition Flowchart
11. Quick-Reference Tables
Interface Members Implicit Modifiers
| Member | Implicit Modifiers | Can You Change? |
|---|---|---|
| Methods | public abstract | Add public explicitly — fine. Change to private/protected — ❌ |
| Fields | public static final | Add explicitly — fine. Change to non-static or non-final — ❌ |
| Nested interfaces (in interface) | public | Cannot make private/protected |
| Nested interfaces (in class) | none | Can be public, protected, private, or default |
Can vs Cannot Interface Checklist
| Action | Allowed? |
|---|---|
| Create an object of an interface | ❌ No |
| Hold a reference to an implementing class | ✅ Yes |
| Interface extends multiple interfaces | ✅ Yes |
| Interface extends a class | ❌ No |
| Class implements multiple interfaces | ✅ Yes |
| Abstract class implements interface partially | ✅ Yes |
| Concrete class implements interface partially | ❌ No — must implement all |
Method in interface declared final | ❌ No |
Method in interface declared private | ❌ No (before Java 9) |
| Field in interface non-final | ❌ No |
| Interface have a constructor | ❌ No |
12. Common Mistakes
Mistake 1: Trying to Instantiate an Interface
1Bird b = new Bird(); // ❌ COMPILE ERROR — Bird is an interfaceFix: Instantiate a concrete implementing class:
1Bird b = new Eagle(); // ✅ Eagle implements BirdMistake 2: Making Interface Method `final`
1public interface Animal {2 final void eat(); // ❌ COMPILE ERROR — illegal modifier final for interface method3}Fix: Remove final — interface methods are abstract by design and must be overridable:
1public interface Animal {2 void eat(); // ✅3}Mistake 3: Using More Restrictive Access in Implementing Class
1public interface Bird {2 void fly(); // public3}4
5public class Eagle implements Bird {6 void fly() { } // ❌ package-private — more restrictive than public7 protected void fly() { } // ❌ protected — more restrictive than public8}Fix:
1public class Eagle implements Bird {2 @Override3 public void fly() { } // ✅ must match or be less restrictive4}Mistake 4: Trying to Modify an Interface Field
1public interface Config {2 int TIMEOUT = 30;3}4
5Config.TIMEOUT = 60; // ❌ COMPILE ERROR — field is finalInterface fields are constants — they can never be changed after initialization.
Mistake 5: Concrete Class Missing Interface Method Implementation
1public interface Shape {2 double area();3 double perimeter();4}5
6public class Circle implements Shape {7 @Override8 public double area() { return 3.14 * 5 * 5; }9 // perimeter() missing ❌ COMPILE ERROR10}Fix: Implement all methods, or declare the class abstract:
1// Option A: implement all2public class Circle implements Shape {3 @Override public double area() { return Math.PI * 5 * 5; }4 @Override public double perimeter() { return 2 * Math.PI * 5; }5}6
7// Option B: declare abstract (let subclass implement perimeter)8public abstract class Circle implements Shape {9 @Override public double area() { return Math.PI * 5 * 5; }10 // perimeter() left for subclass11}Mistake 6: Interface Extending a Class
1class Animal { }2interface Pet extends Animal { } // ❌ COMPILE ERROR — interface cannot extend a classFix: Interfaces can only extend other interfaces:
1interface LivingThing { }2interface Pet extends LivingThing { } // ✅13. Best Practices
- Program to interfaces, not implementations. Always declare reference variables using the interface type:
1 Bird bird = new Eagle(); // ✅ use interface type2 Eagle eagle = new Eagle(); // ❌ avoid — ties you to the concrete class- Name interfaces as adjectives or nouns describing capability:
Flyable,Comparable,Serializable,Runnable,Iterator— notFlyInterfaceorIBird.
- Keep interfaces focused (ISP — Interface Segregation Principle). Don't create one giant interface with 20 methods. Split into smaller, specific interfaces. A class should implement only what it actually needs.
- Use interface constants (
public static final) for true constants only — values that logically belong to the interface's contract and will never change.
- Prefer interfaces over abstract classes when you only need to define a contract and no shared state. This also allows implementors to extend another class freely.
- Use abstract classes when you need to share common state (instance variables) or provide partial implementations that all subclasses should inherit.
- Add
@Overridewhen implementing interface methods — it lets the compiler catch typos in method signatures.
- Use nested interfaces sparingly — only when the nested interface is meaningfully tied to the outer type (like
Map.Entry).
14. Interview Notes
Most Frequently Asked Questions
Q1: What is an interface in Java?
A: An interface is a contract that defines what a class must do (method signatures and constants) without specifying how. It enables abstraction, polymorphism, and multiple inheritance. A class uses implements to adopt an interface and must provide implementations for all its abstract methods.
Q2: What are the three main advantages of interfaces?
A: Abstraction (hides implementation), Polymorphism (interface reference holds different object types; runtime dispatch), and Multiple Inheritance (a class can implement many interfaces, solving the diamond problem that prevents multiple class inheritance).
Q3: What is the diamond problem and how do interfaces solve it?
A: If class C extends both A and B, and both have a method foo(), the compiler cannot determine which foo() to call — this ambiguity is the diamond problem. Interfaces solve it because they only declare method signatures, not implementations. The implementing class always provides its own implementation, eliminating ambiguity.
Q4: What modifiers are implicitly applied to interface methods and fields?
A: Methods are implicitly public abstract. Fields are implicitly public static final (constants).
Q5: Why can't interface methods be final?
A: final prevents overriding. But the entire purpose of interface methods is to be overridden (implemented) by concrete classes. Declaring them final would create an unimplementable method — a direct contradiction.
Q6: Can an abstract class implement an interface?
A: Yes. An abstract class can implement an interface without providing implementations for all methods — it can leave some as abstract for its concrete subclasses to implement. A concrete class, however, must implement every unimplemented abstract method in the chain.
Q7: What is the difference between extends and implements?
A: extends is used when a class inherits from another class, or when an interface inherits from another interface. implements is used only when a class adopts an interface.
Q8: Can an interface extend multiple interfaces?
A: Yes. interface C extends A, B { } is perfectly legal. An interface can extend any number of other interfaces.
Q9: Can you create an object of an interface?
A: No. But you can create a reference variable of interface type that holds an object of a concrete implementing class:
1Bird b = new Eagle(); // ✅Q10: What is a nested interface?
A: An interface declared inside another interface or class. When nested inside an interface, it must be public. When nested inside a class, it can be any access modifier. The famous example is Map.Entry inside Map.
Q11: What changed in Java 8 for interfaces?
A: Java 8 introduced default methods (concrete methods with a body, using the default keyword) and static methods in interfaces. This partially blurred the line between abstract classes and interfaces. Java 9 further added private methods. These are covered in Part 2.
Q12: Can an interface have a constructor?
A: No. Interfaces cannot be instantiated, so constructors serve no purpose in them.
15. Practice Questions
Easy
- What keyword does a class use to adopt an interface?
- What are the implicit modifiers on interface methods?
- What are the implicit modifiers on interface fields?
- Can you instantiate an interface? Can you hold a reference to an implementing class?
- Can an interface extend a class?
Medium
- Create an interface
Shapewith methodsarea()andperimeter(). Implement it withCircleandRectangleclasses. Store both in aShape[]array and call both methods on each.
- Demonstrate the diamond problem using classes (show why it fails), then solve it using interfaces.
- Create an interface
FlyableandSwimmable. Create a classDuckthat implements both. Call methods through both interface reference types.
- Write a nested interface
Map.Entrystyle example with an outer interfaceLibrarycontaining a nested interfaceBook. Implement both using a class.
- What is the output of the following code?
1 interface A { int X = 10; }2 interface B { int X = 20; }3 class C implements A, B {4 public void show() {5 System.out.println(A.X);6 System.out.println(B.X);7 }8 }Hard
- Create an abstract class
Vehiclethat implements an interfaceDrivable(with methodsstart()andstop()). The abstract class should implementstart()but leavestop()for concrete children. Create a concreteCarclass that completes the hierarchy.
- Explain why the following does not compile and fix it:
1 interface Greeter { void greet(); }2 class Hello implements Greeter {3 protected void greet() { System.out.println("Hello!"); }4 }- Create an interface
Sortablewith a constantASCENDING = 1andDESCENDING = -1. Implement it in aNumberSorterclass. Try to change the constant from the implementing class and explain what happens.
- Explain the difference between an interface and an abstract class with respect to constructors, instance variables, and multiple inheritance. Give a code example for each difference.
- Create a class that implements a nested interface declared inside another interface. Show how to reference the nested interface type from an external class.
16. Summary Cheat Sheet
1┌─────────────────────────────────────────────────────────────────────────────┐2│ JAVA INTERFACES — QUICK SUMMARY (Part 1) │3├─────────────────────────────────────────────────────────────────────────────┤4│ DEFINITION │5│ Contract: defines WHAT a class must do, not HOW. │6│ Keyword: 'interface'. Implemented with 'implements'. │7├─────────────────────────────────────────────────────────────────────────────┤8│ THREE KEY ADVANTAGES │9│ 1. Abstraction — hides implementation from caller │10│ 2. Polymorphism — interface reference holds different concrete objects │11│ 3. Multiple Inh. — one class implements many interfaces (no diamond issue)│12├─────────────────────────────────────────────────────────────────────────────┤13│ METHODS │14│ Implicitly: public abstract │15│ Cannot be: final, private, protected (pre-Java 9) │16├─────────────────────────────────────────────────────────────────────────────┤17│ FIELDS │18│ Implicitly: public static final (constants) │19│ Cannot be changed (final) or made private │20├─────────────────────────────────────────────────────────────────────────────┤21│ IMPLEMENTATION RULES │22│ Concrete class: must implement ALL abstract methods │23│ Abstract class: may implement some or none │24│ Override access: cannot be more restrictive than public │25│ A class can implement multiple interfaces: implements A, B, C │26├─────────────────────────────────────────────────────────────────────────────┤27│ NESTED INTERFACES │28│ In interface: must be public │29│ In class: any access modifier (public/protected/private/default) │30│ Access: OuterType.NestedInterface │31├─────────────────────────────────────────────────────────────────────────────┤32│ INTERFACE vs ABSTRACT CLASS — KEY DIFFERENCES │33│ abstract class → 'abstract' interface → 'interface' │34│ child uses → 'extends' child uses → 'implements' │35│ variables → any type variables → public static final only │36│ constructor → ✅ allowed constructor → ❌ not allowed │37│ multiple inh → ❌ multiple inh → ✅ │38│ partial impl → possible partial impl → only via abstract class │39└─────────────────────────────────────────────────────────────────────────────┘End of Chapter — Java Interfaces (Part 1)
Next: Part 2 — Java 8 Default Methods · Static Methods in Interfaces · Java 9 Private Methods · Functional Interfaces · Lambda Expressions
Practice & Implement
Apply what you learned in Interfaces — Fundamentals
Create a `Student` class that implements `Comparable<Student>` by GPA (descending). Sort 3 students and print in order.
Bob: 3.9 Alice: 3.5 Charlie: 3.2
Mastery check
How well can you recall this?
Finished this lesson?