Title here
Summary here
Both abstract classes and interfaces are used to achieve abstraction β hiding implementation details and exposing behavior. But they serve different purposes in Javaβs object-oriented design.
Feature | Abstract Class | Interface |
---|---|---|
Inheritance | extends (single) | implements (multiple allowed) |
Methods | Can have abstract and concrete methods | Only abstract methods (Java 7), also default/static methods (Java 8+) |
Constructors | Yes | No |
Fields | Can have variables with any access level | Only public static final constants |
Access Modifiers | Can use all modifiers | Members are implicitly public |
Purpose | “Is-a” relationship | “Can-do” or capability-based contracts |
abstract class Animal {
String name;
Animal(String name) {
this.name = name;
}
abstract void makeSound(); // abstract method
void sleep() {
System.out.println(name + " is sleeping...");
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
void makeSound() {
System.out.println(name + " says: Woof!");
}
}
interface Flyable {
void fly(); // implicitly public and abstract
}
interface Swimmable {
void swim();
}
class Duck implements Flyable, Swimmable {
@Override
public void fly() {
System.out.println("Duck is flying!");
}
@Override
public void swim() {
System.out.println("Duck is swimming!");
}
}
Version | Interface Capability |
---|---|
Java 7 | Only abstract methods |
Java 8 | default and static methods allowed |
Java 9+ | private methods inside interfaces also allowed |
Often, you’ll see both used together:
abstract class Vehicle {
abstract void start();
}
interface Electric {
void charge();
}
class Tesla extends Vehicle implements Electric {
void start() {
System.out.println("Tesla is starting silently...");
}
public void charge() {
System.out.println("Tesla is charging...");
}
}
Create an abstract class Shape
with:
area()
display()
that prints βCalculating areaβ¦βCreate concrete subclasses:
Circle
with a radiusRectangle
with length and widthCreate an interface Colorable
with:
void setColor(String color)
Implement Colorable
in the subclasses and allow setting and displaying color.
Shape
referencesReady to tackle Static Keyword or move into Composition vs Inheritance next?