When to use an abstract class in Java – J038

by Nov 3, 2015

DeegeU Java Course

The “When to use an abstract class in Java” video is part of a larger free online class called “Free Java Course Online”. You can find more information about this class on “Free Java Course Online” syllabus.

Transcript – When to use an abstract class in Java

What is an abstract class, and when do you use an abstract class in Java? That’s coming up next.

When we look at a recipe for making bread, there’s really more than one recipe in front of us. Baking bread at altitude has a different recipe than baking bread at sea-level. What we really have is a template recipe for making bread, and if we’re at altitude we insert instructions for altitude baking. If we’re at sea level, we insert instructions for low altitude baking. The template bread recipe cannot be used until we insert the instructions for high or low altitudes. We need a way to handle this situation in our Java classes.

In Java, an abstract class is a class definition where we don’t provide all the implementation details. The class has the keyword “abstract” added to it here. We denote abstract classes in our diagrams by making the class name in italics.

We can also mark some of the methods as abstract. That means we just provide the method signature and return type, but we don’t provide the Java block that implements the method. We mark the methods with the keyword “abstract”. Note the method has no braces, no implementation, and just ends with a semi-colon. Again we use italics for abstract methods in our diagrams.

If we declare a class as abstract, the methods may or may not be abstract. We don’t need to have any abstract methods. It would be weird, because what would be the point, but we can do it. The opposite isn’t true. If we mark any method as abstract, we must mark the class as abstract.

abstract public class BreadMachine {
    abstract void addIngredients();

    void setRecipeName(String name){ 
        this.recipeName = name; 
    }

    boolean isDone() {
        return timerEnded && isRisen;
    }   
}

Another note. We can’t have a method that is abstract and private. We couldn’t access it, and there’s really no point. If you’re protecting it for subclasses, you’ll want to use protected.

Other than that, there’s no difference between an abstract class and a regular class. We can have implemented methods, attributes, and static variables. We can even have methods that call abstract methods. That’s where the power is. Like in our bread recipe, we know we have different ingredient and cooking steps. So we can have a cook method that calls these steps, and we’ll specify what to do in a child class. So how does the Java abstract class help us?

Abstract classes differ from classes because abstract classes can’t be instantiated, the functionality isn’t complete. This won’t work. We can’t instantiate an abstract class. If we try, our Java program won’t even compile. Our bread recipe has all the steps, but leaves out what to do in key parts. Abstract classes give us a way we can create a high altitude bread recipe, and a low altitude bread recipe. These are implemented as child classes that we can instantiate.

We use abstract classes when we know the methods, but we don’t know how they would be implemented. In previous lectures about subclasses, we just left the method blank. It’s a much better practice to not implement the method at all. There are very few instances where implementing an empty method in Java is a good idea. The reason is, if someone were using our class, they wouldn’t know they needed to provide an implementation. (*) When we mark the method as abstract, anyone using our class has no choice but to provide an implemented child class. They can’t instantiate the class otherwise.

This is called compile time safety. Compile-time safety ensures that any classes that extend our abstract class must provide the bare minimum functionality to work.

Another reason to implement abstract classes is to provide functionality we know all sub classes will use. We know all our bread recipes will have a “makeDough” method. So we can provide the implementation. This way we don’t have to repeat the method in every subclass. Repeating code in subclasses is universally bad.

Now that we’ve seen abstract classes, I’ll add a word of caution. Abstract classes force you to expose your class as inheritable. We can’t mark an abstract class as final, since to use an abstract class, we must have a subclass that implements it. That might not be a great idea, because we can run into many problems as we’ve seen in previous lessons. In fact with Java 8, I’m quickly running out of places where I’d want to use abstract classes. We’ll see why when we get to interfaces and defender methods.

Hey! Thanks for watching the video. If you have any questions, let me know in the comments or on DeegeU.com! New videos come out each week, so make sure you subscribe. That puts new videos in your YouTube feed. If you liked the video, you know what to do.

I’ll see you in the next tutorial!

<p><script async="" src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- DeegeU - Right Side -->
<ins class="adsbygoogle" style="display:inline-block;width:336px;height:280px" data-ad-client="ca-pub-5305511207032009" data-ad-slot="5596823779"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></p>

Tools Used

  • Java
  • NetBeans

Media Credits

All media created and owned by DJ Spiess unless listed below.

  • No infringement intended

Get the code

The source code for “When to use an abstract class in Java” can be found on Github. If you have Git installed on your system, you can clone the repository by issuing the following command:

 git clone https://github.com/deege/deegeu-java-intro.git

Go to the Support > Getting the Code page for more help.

If you find any errors in the code, feel free to let me know or issue a pull request in Git.

Don’t miss another video!

New videos come out every week. Make sure you subscribe!

Comments

comments

DJ Spiess

DJ Spiess

Your personal instructor

My name is DJ Spiess and I’m a developer with a Masters degree in Computer Science working in Colorado, USA. I primarily work with Java server applications. I started programming as a kid in the 1980s, and I’ve programmed professionally since 1996. My main focus are REST APIs, large-scale data, and mobile development. The last six years I’ve worked on large National Science Foundation projects. You can read more about my development experience on my LinkedIn account.

Pin It on Pinterest

Share This