Junior — Middle
How to properly implement abstract classes in interfaces and what are their differences?
sobes.tech AI
Answer from AI
In Java, an abstract class is a class that can contain both implemented methods and abstract methods (without implementation). It serves as a base template from which subclasses inherit. An interface initially contained only abstract methods (without implementation), but starting from Java 8, interfaces can include methods with implementations (default and static methods).
Differences:
- An abstract class can contain state (fields), while an interface only has constants (final static fields).
- A class can inherit only one abstract class but can implement multiple interfaces.
- An abstract class can have constructors, whereas an interface cannot.
Example of an abstract class:
public abstract class Animal {
abstract void sound();
void breathe() {
System.out.println("Breathing");
}
}
Example of an interface:
public interface Flyable {
void fly();
default void land() {
System.out.println("Landing");
}
}