Get startedGet started for free

Making the car class abstract

1. Making the car class abstract

While working with OOP and inheritance, a concept called Abstract classes helps us compose more reusable classes.

2. Explaining abstract class

So, what is an abstract class? Consider the idea of a Car. When purchasing, you understand what a car is, but you choose a specific type, like a Toyota or a Mercedes.

3. Food analogy for abstract class

The same analogy extends to food; when dining out, you don’t simply ask for food but specify items like bread, pasta, or rice. In this analogy, food serves as a placeholder for something edible, just as the term Car acts as a placeholder for a specific type of Car.

4. Understanding abstract classes

You wouldn’t classify a motorcycle as a car because it lacks defining characteristics like four wheels, a windscreen, and a steering wheel. Abstract classes operate similarly to the Car concept. Abstract classes are designed to hold information related to a specific group of classes that are meant to inherit from them. Yet, you cannot create instances of an abstract class as objects using the new keyword. For example, you cannot buy something that is just a Car, since you would buy a Toyota Car or a Mercedes Car. In essence, abstract classes exist to provide a blueprint for subclasses.

5. Car abstract class

We can define and mark a Car class as abstract by inserting the abstract keyword before the class name. This class includes an abstract void drive() method. Typically, abstract classes have methods that only have their names and parameters without a pair of curly braces; therefore, they do not have code implementation as a typical method would.

6. Abstract methods

Classes like Toyota and Porsche can inherit from the Car class and implement the drive() method in their own ways. In this manner, the Car class's abstract drive() method serves merely as a blueprint, allowing each subclass to provide its unique implementation.

7. Creating concrete methods

Abstract Classes can have methods with code implementation for the Subclasses to inherit, as not all methods have to be abstract. When a method in an abstract class has code implementation, it is called a concrete method. We used concrete methods when we learned about inheritance, but they can also be used in abstract classes. To give an example in the Car class, we can create a getTopSpeed() method that returns a private topSpeed property that is part of the Car abstract class.

8. Let's practice!

In summary, abstract classes facilitate the organization of relationships between classes, creating exciting hierarchies that mirror real-world interactions. Now, it’s your turn to dive into using abstract classes and crafting abstract methods!