Interface Changes In Java Tutorials
Programming
🔷 Interface Changes
Before Java 8
An interface contains only abstract methods
A method without a body is called an abstract method
A class implements an interface using the
implementskeywordA class must implement all abstract methods, otherwise it will cause a compile-time error
Example (Before Java 8)
java
interface Vehicle {
void startVehicle();
}
class Car implements Vehicle {
public void startVehicle() {
System.out.println("Car started...");
}
}
class Bus implements Vehicle {
public void startVehicle() {
System.out.println("Bus started...");
}
}
class Bike implements Vehicle {
public void startVehicle() {
System.out.println("Bike started...");
}
}❗ Problem
If we add a new method inside the Vehicle interface:
java
void stopVehicle();All implementing classes (Car, Bus, Bike) must implement this method.
Otherwise, they will fail at compile time.
Solution in Java 8 – Default & Static Methods
Java 8 allows concrete methods inside interfaces using:
defaultkeywordstatickeyword
This feature was introduced for backward compatibility.
🔹 Default Method
Has a method body
Can be overridden in implementing classes
Provides a default implementation
🔹 Static Method
Belongs to the interface
Cannot be overridden
Must be called using the interface name
Example – Interface with Default & Static Methods
java
interface Vehicle {
void start(); // abstract method
default void m1() {
System.out.println("Default Method m1()");
}
default void m2() {
System.out.println("Default Method m2()");
}
static void clean() {
System.out.println("Cleaning completed...");
}
}
// Implementation Class
public class Car implements Vehicle {
public void start() {
System.out.println("Car started...");
}
public static void main(String[] args) {
Car c = new Car();
c.start(); // calling abstract method
c.m1(); // calling default method
Vehicle.clean(); // calling static method
}
}📝 Important Points
✔ Interface can have multiple default and static methods
✔ Default methods can be overridden
✔ Static methods cannot be overridden
✔ Static methods must be called using interface name
✔ Introduced for backward compatibility