Abstract Classes in JAVA
Abstract Classes in JAVA
// Concrete method
void sleep() {
System.out.println("Sleeping...");
}
}
// Concrete subclass
class Dog extends Animal {
// Implementing the abstract method
void makeSound() {
System.out.println("Barking...");
}
}
Explanation:
Animal is an abstract class with an abstract method
makeSound().
Dog extends Animal and implements makeSound().
The sleep() method is already implemented in
Animal, so Dog can use it directly.
// Constructor
Vehicle(String brand) {
this.brand = brand;
System.out.println("Vehicle constructor called");
}
void start() {
System.out.println(brand + " Car is starting...");
}
}
Output:
Vehicle constructor called
Toyota Car is starting...
Explanation:
The Vehicle abstract class has a constructor.
The Car class calls the parent constructor using
super(brand).
This allows initialization of the brand attribute before
calling start().
Key Takeaways
✔ Abstract classes cannot be instantiated.
✔ They can contain abstract and concrete methods.
✔ Subclasses must implement all abstract methods or
declare themselves as abstract.
✔ Constructors are allowed in abstract classes.
✔ Static methods are allowed, but they cannot be abstract.
Scenario:
Example:
abstract class Animal {
abstract void makeSound(); // Must be implemented by subclasses
void sleep() {
System.out.println("Sleeping...");
}
}
Scenario:
Example:
abstract class Vehicle {
String brand;
Vehicle(String brand) {
this.brand = brand;
}
void stop() {
System.out.println(brand + " has stopped.");
}
}
void start() {
System.out.println(brand + " Car starts with a key.");
}
}
void start() {
System.out.println(brand + " Bike starts with a kick.");
}
}
Assignment
1. Banking System (Defining Account Types)
Scenario:
Banks have different types of accounts like savings and current accounts. They all share a
method to calculate interest but implement it differently.
Scenario:
A company has permanent and contract employees, both of whom receive salaries but have
different ways of calculating pay.