DEV Community

Cover image for Abstract Classes in Java – Breaking It Down
Bellamer
Bellamer

Posted on

2

Abstract Classes in Java – Breaking It Down

What is an Abstract Class?

An abstract class is like a blueprint for other classes. You can’t create an object directly from an abstract class. Instead, you use it as a foundation for other classes that can build upon it and fill in the details.

Why Use Abstract Classes?

Abstract classes are useful when you want to define a general concept that has some shared features, but you also want to leave room for specific details that can vary in different situations. For example, you might have a general concept of an "Animal" that includes common features like eating or sleeping, but different animals might eat or sleep in different ways.

Creating an Abstract Class

Here’s how you might create an abstract class called Animal:

public abstract class Animal {
    abstract void makeSound();  // Abstract method, no body

    void sleep() {
        System.out.println("This animal sleeps.");
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, makeSound() is an abstract method, meaning it doesn’t have a body yet. The sleep() method, however, is fully implemented.

Extending an Abstract Class

Now, let’s create some classes that extend the Animal class:

public class Dog extends Animal {
    void makeSound() {
        System.out.println("The dog barks.");
    }
}

public class Cat extends Animal {
    void makeSound() {
        System.out.println("The cat meows.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Both Dog and Cat classes must provide their own version of the makeSound() method, but they inherit the sleep() method as is.

Abstract Class vs. Interface

  • Inheritance: A class can extend only one abstract class but can implement multiple interfaces.
  • Method Implementation: An abstract class can have both abstract methods (without a body) and fully implemented methods. An interface (before Java 8) can only have abstract methods.
  • Constructor: Abstract classes can have constructors, while interfaces cannot.

Partial Implementation

An abstract class is great when you have some methods that should be shared among all child classes, but you also want to force some methods to be defined by those child classes.

public abstract class Bird extends Animal {
    void move() {
        System.out.println("The bird flies.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, any class that extends Bird will inherit both the move() method and the sleep() method from Animal, but still needs to implement makeSound().

Challenge: Try It Yourself!

  1. Create an abstract class called Vehicle with an abstract method startEngine().
  2. Make two classes, Car and Motorcycle, that extend Vehicle and implement the startEngine() method.
  3. Add a common method to Vehicle, like stopEngine(), and see how it works in the child classes.

Conclusion

Abstract classes in Java provide a way to create a shared foundation for related classes while leaving room for those classes to define specific details. They strike a balance between shared functionality and flexibility, making your code both powerful and reusable.

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay