What is the difference between an abstract class and an abstract method, as well as between an abstract method and an interface?
sobes.tech AI
Answer from AI
An abstract class is a class that cannot be instantiated directly. It can contain abstract and non-abstract methods, fields, and constructors. It is used to define common characteristics and behaviors for subclasses.
An abstract method is a method without an implementation (body). It is declared with the abstract keyword in an abstract class or interface. Subclasses of an abstract class or a class implementing an interface are required to provide implementations for all abstract methods.
Difference between an abstract method and an interface:
| Characteristic | Abstract Method | Interface |
|---|---|---|
| Declaration location | Abstract class, Interface | Interface |
| Implementation requirement | Subclass of abstract class, class implementing interface | Class implementing interface |
| Body presence | No | No (until Java 8 - only declaration, with Java 8 - default and static methods with bodies) |
| Access modifiers | Public, protected, default (in abstract class); public (in interface) | Public |
An interface is a fully abstract "contract," a set of abstract methods (until Java 8) and constants. A class can implement multiple interfaces. It is used to define common behavior that can be implemented by different classes and to achieve multiple inheritance of behavior.
// Example of an abstract class
abstract class Animal {
String name;
// Abstract method
abstract void makeSound();
// Non-abstract method
void setName(String name) {
this.name = name;
}
}
// Example of a class inheriting an abstract class
class Dog extends Animal {
@Override
void makeSound() { // Implementation of abstract method
System.out.println("Woof");
}
}
// Example of an interface
interface Flyable {
// Abstract method (implicitly public abstract)
void fly();
// Static method (from Java 8)
static void describeFlying() {
System.out.println("Ability to fly.");
}
// Default method (from Java 8)
default void land() {
System.out.println("Landing...");
}
}
// Example of a class implementing the interface and inheriting an abstract class
class Bird extends Animal implements Flyable {
@Override
void makeSound() {
System.out.println("Chirp");
}
@Override
public void fly() { // Implementation of interface's abstract method
System.out.println("Flying high!");
}
}