Loading content...
Loading content...
🔷 Interface Changes
An interface contains only abstract methods
A method without a body is called an abstract method
A class implements an interface using the implements keyword
A class must implement all abstract methods, otherwise it will cause a compile-time error
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...");
}
}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.
Java 8 allows concrete methods inside interfaces using:
default keyword
static keyword
This feature was introduced for backward compatibility.
Has a method body
Can be overridden in implementing classes
Provides a default implementation
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
}
}✔ 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