Table of Contents
Abstract classes are classes in Java that contain abstract methods which let children classes provide the implementation. Defining abstract classes is useful for when you want different implementation for the same method.
Creating an Abstract Class
Let's say we are trying to get from point A to point B. This is represented by our abstract class Transportation.java
:
JAVApublic abstract class Transportation {
public abstract void travel();
}
Our new Transportation
class is abstract which means you cannot actually make an object directly from it.
Extending an Abstract Class
While you can't make objects directly from an abstract class, you can make objects from the classes that extend it.
Let's define two different modes of transportation, by extending that abstract class:
JAVApublic class Train extends Transportation {
public void travel() {
System.out.println("Choo choo!");
}
}
public class Car extends Transportation {
public void travel() {
System.out.println("Beep beep!");
}
}
Our classes Train
and Car
extend our abstract class Transportation
, which forced both of them to provide an implementation for the travel()
abstract method.
Now we can use our new classes, like this:
JAVApublic class Main {
public static void main(String[] args) {
Train train = new Train();
train.travel();
Car car = new Car();
car.travel();
}
}
BASHChoo choo!
Beep beep!
This right here is the power of abstract classes. Their job is just to define a contract, and any class that extends it agrees to that contract. In this case, the contract is that if you want to be a mode of transportation, you must be able to travel. Both Train
and Car
implemented that method and thus became valid types of transportation.
- How to Install Node on Windows, macOS and Linux
- Getting Started with Express
- How to deploy a .NET app using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js