Abstract and concrete
- Java course
- Intermediate
- Lesson 55/116
- 4 min
Learn concrete methods in abstract classes.
Concrete methods in abstract classes
An abstract class can contain both abstract and concrete methods. Concrete methods have a body; subclasses use them as is. This is the way to gather common behavior in one place.
Example: abstract class Vehicle { abstract void start(); void stop() { System.out.println("Stopped"); } }. Here start is abstract; the subclass writes it. But stop is concrete; its body is given in the abstract class. The subclass can use stop without overriding it. This is where abstract class diverges from interface: unlike an interface it carries common state and behavior. It reduces code duplication.
Sharing concrete methods
Concrete methods are written once in an abstract class; all subclasses inherit them. This is a powerful way to keep common behavior in one place.
Example: if you define a void describe() concrete method in the Vehicle abstract class, both Car and Truck use it. If you change the method, all subclasses update. This makes maintenance easier. A subclass may override the method; but it is not forced to. The abstract class centralizes common behavior. This feature is the main difference between abstract class and interface. An interface had no bodyful methods except default ones.
Practice Add a concrete method to the Vehicle class
Define an abstract class Vehicle. Add the abstract void start(); signature and a void stop() concrete method with a body that runs System.out.println("Stopped");. Write class Car extends Vehicle; write the public void start() method with a body that runs System.out.println("Started");. In main create Car c = new Car(); then call c.start() and c.stop().
Starter code
// Define the abstract Vehicle class
// start is abstract, stop is concrete
// Write the Car subclass
// Call start and stop in mainSample solution
abstract class Vehicle {
abstract void start();
void stop() {
System.out.println("Stopped");
}
}
class Car extends Vehicle {
public void start() {
System.out.println("Started");
}
}
class Main {
public static void main(String[] args) {
Car c = new Car();
c.start();
c.stop();
}
}Expected output
Started Stopped
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a concrete method?
- A bodyful method Correct answer
- A bodyless method
- A static method
- A private method
Explanation: A concrete method is written with a body.
2 Complete the subclass declaration
class Car ____ Vehicle {
public void start() { System.out.println("Çalıştı"); }
}
class Car extends Vehicle {
public void start() { System.out.println("Çalıştı"); }
}
Explanation: The extends keyword inherits from an abstract class.
3 Match the abstract and concrete concepts
| Term | Meaning |
|---|---|
abstract |
Bodyless signature |
concrete |
Bodyful method |
extends |
Inheritance keyword |
super |
Parent access |