Interfaces in java and how they are different with inheritance
Interfaces in java and how they are different with inheritance
(Things To Know)
It’s kinda like a to-do list for a class. No actual code — just the method names and their
parameters. You implement the details later.
interface Animal {
void makeSound(); // method with no body
}
Interfaces used to only allow abstract methods — method signatures with no body. Like:
void run();
Now you can have method bodies using the default keyword.
Animal.printInfo();
4. No Constructors
Interfaces can’t have constructors. Why? Because you can't create objects of an interface
directly. They’re not real-world things — they’re more like guidelines.
A class in Java can’t extend more than one class. But it can implement multiple interfaces.
That’s Java's way of doing multiple inheritance:
class C implements A, B {
public void doA() { System.out.println("A"); }
public void doB() { System.out.println("B"); }
}
Which means:
If an interface has exactly one abstract method, it's called a functional interface — used with
lambda expressions.
@FunctionalInterface
interface Greeting {
void sayHello();
}
Use inheritance when you want to share actual code and create a strong "is-a"
relationship.
➤ Example: Car extends Vehicle
Use interface when you want to define a capability or role that multiple classes can play.
➤ Example: Bird implements Flyable