In Java, both interfaces and abstract classes are used to define abstract methods. However, there are key differences between them. An interface defines a contract that classes must follow, whereas an abstract class provides a partial implementation. Interfaces use the `interface` keyword, while abstract classes use the `abstract` keyword.
Here’s an example of an interface and an abstract class:
interface Animal {
void sound();
}
abstract class Bird {
abstract void fly();
void eat() {
System.out.println("Bird is eating");
}
}
In this example, the interface `Animal` defines a method without implementation, while the abstract class `Bird` provides both an abstract and a concrete method. Understanding when to use an interface or an abstract class is important for designing flexible and reusable Java programs.
Leave a Reply