Java Interview Questions

Previous Java Interview Questions Next

Java Interfaces - Theory Questions

1. What is an interface in Java and what are its key characteristics?

An interface in Java is a reference type that contains only abstract methods (until Java 7), default methods, static methods, and constant declarations. Key characteristics:
- Defines a contract that implementing classes must follow
- Supports multiple inheritance
- All methods are implicitly public abstract (until Java 8)
- All variables are implicitly public static final
- Cannot be instantiated directly
- Used to achieve abstraction and polymorphism

2. What is the syntax for declaring and implementing interfaces?

Interface Declaration:
public interface InterfaceName {
// constant declarations
// method signatures
}

Interface Implementation:
class ClassName implements InterfaceName {
// implement all abstract methods
}

A class can implement multiple interfaces separated by commas.

3. What are the differences between abstract classes and interfaces?

Abstract Class:
- Can have abstract and concrete methods
- Can have instance variables
- Supports constructors
- Single inheritance only
- Various access modifiers allowed
Interface:
- All methods public abstract (until Java 8)
- Only static final variables
- No constructors
- Multiple inheritance supported
- All members implicitly public

4. What are default methods in interfaces (Java 8 feature)?

Default methods allow interfaces to have method implementations:
interface Vehicle {
default void start() {
System.out.println("Vehicle starting");
}
}

Features:
- Provide backward compatibility
- Can be overridden by implementing classes
- Use default keyword
- Help in evolving interfaces without breaking existing implementations

5. What are static methods in interfaces (Java 8 feature)?

Static methods in interfaces are similar to static methods in classes:
interface MathOperations {
static int add(int a, int b) {
return a + b;
}
}

Characteristics:
- Belong to the interface, not implementing classes
- Cannot be overridden or inherited
- Called using interface name: MathOperations.add(5, 3)
- Provide utility methods related to interface

6. What are private methods in interfaces (Java 9 feature)?

Private methods allow code sharing within interface without exposing implementation:
interface DatabaseOperations {
default void connect() {
establishConnection();
}
private void establishConnection() {
// connection logic
}
}

Benefits:
- Reduce code duplication in default methods
- Hide helper method implementation
- Improve code maintainability

7. How does multiple inheritance work with interfaces?

Java supports multiple inheritance through interfaces:
class SmartPhone implements Phone, Camera, Computer {
// must implement all abstract methods from all interfaces
}

Advantages:
- A class can have multiple behaviors
- No diamond problem (until Java 7)
- Flexible design
With default methods (Java 8+), diamond problem is resolved using these rules:
- Class implementation wins over interface default
- Most specific interface default wins
- Explicit override required for conflicts

8. What is the diamond problem with default methods and how is it resolved?

The diamond problem occurs when:
interface A { default void method() { ... } }
interface B extends A { default void method() { ... } }
interface C extends A { default void method() { ... } }
class D implements B, C { } // Conflict!

Resolution rules:
1. Class wins: If class overrides, use class method
2. Most specific: Sub-interface wins over super-interface
3. Explicit choice: Use B.super.method() or C.super.method()

9. What are functional interfaces?

A functional interface has exactly one abstract method:
@FunctionalInterface
interface Calculator {
int calculate(int a, int b);
}

Characteristics:
- Can have multiple default and static methods
- Used extensively with lambda expressions
- Annotated with @FunctionalInterface
- Examples: Runnable, Comparator, Predicate

10. What is marker interface and what are its uses?

A marker interface is an empty interface with no methods or fields:
interface Serializable { } // marker interface
Uses:
- Provide runtime type information
- Mark classes for special treatment
- Examples: Serializable, Cloneable, Remote
Modern alternative: Use annotations which provide more flexibility

11. Can interfaces extend other interfaces?

Yes, interfaces can extend other interfaces using extends keyword:
interface Animal { void eat(); }
interface Mammal extends Animal { void breathe(); }
interface Dog extends Mammal { void bark(); }

Features:
- Multiple inheritance allowed for interfaces
- Implementing class must implement all methods from entire hierarchy
- Provides interface inheritance hierarchy

12. What are the access rules for interface members?

All interface members have specific access rules:
- Methods: Implicitly public (cannot use private, protected, or package-private)
- Abstract methods: Always public abstract
- Default methods: Always public (can be overridden as public)
- Static methods: Always public (can be called without implementation)
- Variables: Always public static final (constants)

13. How do interfaces support polymorphism?

Interfaces enable polymorphism through interface references:
interface Shape { void draw(); }
class Circle implements Shape { public void draw() { ... } }
class Square implements Shape { public void draw() { ... } }

Shape shape1 = new Circle(); // Polymorphic reference
Shape shape2 = new Square(); // Polymorphic reference
shape1.draw(); // Calls Circle's draw()
shape2.draw(); // Calls Square's draw()

14. What is the purpose of the @FunctionalInterface annotation?

The @FunctionalInterface annotation:
- Indicates the interface is intended to be a functional interface
- Provides compile-time checking
- Documents the intent clearly
- Prevents accidental addition of second abstract method
Example:
@FunctionalInterface
interface Transformer {
String transform(String input);
// Only one abstract method allowed
}

15. Can interfaces have constructors?

No, interfaces cannot have constructors because:
- Interfaces cannot be instantiated directly
- They represent contracts, not implementations
- Constructors are for object initialization, but interfaces don't have state
- All variables in interfaces are static final constants
Object creation happens through implementing classes that have constructors.

16. What are nested interfaces?

Interfaces can be declared inside classes or other interfaces:
Interface inside class:
class Outer {
interface Inner {
void method();
}
}

Interface inside interface:
interface Outer {
interface Inner {
void method();
}
}

Nested interfaces are implicitly static.

17. How do interfaces help in achieving loose coupling?

Interfaces promote loose coupling by:
- Separation of contract and implementation
- Program to interface, not implementation principle
- Easy substitution of implementations
- Better testability through mocking
Example:
interface Database {
void connect();
}
// Can switch between MySQL, Oracle, MongoDB easily

18. What are the common built-in functional interfaces in Java?

Java provides several functional interfaces in java.util.function package:
- Predicate<T>: boolean test(T t) - for conditions
- Function<T,R>: R apply(T t) - for transformations
- Consumer<T>: void accept(T t) - for operations
- Supplier<T>: T get() - for value suppliers
- Runnable: void run() - for tasks
- Comparator<T>: int compare(T o1, T o2) - for sorting

19. What is the difference between abstract method and default method?

Abstract Method:
- No implementation provided
- Must be implemented by concrete class
- Traditional interface method
- Cannot be static or final
Default Method:
- Provides implementation
- Optional to override in implementing class
- Java 8+ feature
- Uses 'default' keyword
- Can be overridden by implementing class

20. What are the best practices for designing interfaces?

Design guidelines:
- Keep interfaces focused and cohesive (Single Responsibility)
- Use meaningful names that describe capability
- Prefer multiple specific interfaces over one large interface
- Use @FunctionalInterface for functional interfaces
- Document the contract clearly
- Consider backward compatibility when evolving
- Use default methods for extending existing interfaces
- Keep interfaces minimal and essential

Previous Java Interview Questions Next