15.1 Abstract Classes

Imagine you wrote a class called Animal, which three classes Dog, Cat, and Cow extended. In the Animal you had a method called noise(). What would you put in it? Each animal makes a different sound, so implementing the method in the Animal class would be meaningless.
Enter Abstract Classes which are incomplete classes that can contain both abstract and concrete methods. What does it mean to be an incomplete class? Basically, you cannot create an instance of an abstract class, which makes sense. You can’t just make an “everything” animal(though it would be cool). Instead, you create an instance of one of the child classes. Each child class will be required to implement all abstract methods given in the abstract parent.
You can add a constructor to an abstract class(not required though), and it will be called when any of the child classes are called. Here’s how to make an abstract class.
abstract class Animal { public abstract void noise(); } public class Dog extends Animal { public void noise() { System.out.println("Woof!"); } }
Notice how the abstract method has no curly braces and no code body. All classes that extend the abstract class are required to implement abstract methods. In this example, all three of our animals will have noises they make.

Next Section

15.2 Abstract Methods
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.