DEV Community

John Hill
John Hill

Posted on

Super, Sub, and Abstract Classes

When we get into coding anyone who has been coding for any period of time knows we want to keep our code DRY. Whenever you see yourself copying methods and variables from one class to another we may want to set up a relationship between the classes.

An easy way to look at this would be a vehicle. If someone was to ask you to draw a vehicle some people may draw a car, a truck, or a motorcycle. Similarly if I google a picture of a car it shows me pictures of hundreds of different types of cars. In this regard the more abstract the concept the higher in the class it should be, with vehicle being the upmost Super class in this case. Similarly the more specific it gets the more sub it would be with maybe 2017 Ford Mustang GT being the most specific so being the final subclass in the tree.

When we look at Super and sub classes it is important to know what is inherited vs what is accessible/callable. As you know if you have been working with java for any amount of time we designate things private, public, and protected. A subclass inherits everything from a Superclass, but not everything is necessarily accessible in the subclass. If you have a private method or variable you cannot call them directly in the subclass. As in other cases public methods and variables are both accessible and are also inherited to the class.

The biggest designation to get used to when using Super and subclasses would probably be protected. A protected method or variable is inherited and callable in the subclass but is not callable in non related classes. For instant if we had a protected method in car it could not be accessed in boat for instance, but that method would be callable in Ford.

So how do we set up these relationships in Java. In Java we use extends to set up the relationship between classes. the subclass extends the superclass to let the compiler know it is the sublcass of the super.

public class Car extends Vehicle { 

}

In this set up there is a flaw though we want to have the super class vehicle and we want a method drive in this super class but each subclass needs to implement drive in its own way and we don't want people to be able to create a vehicle because technically vehicles don't exist on their own. This is where abstract classes and methods come into play.


public abstract class Vehicle {

protected abstract void drive();

}

Above we have created the abstract class vehicle which contains the abstract method drive. It is import that any subclass of vehicle must implement the method drive. Any subclass that does not implement the abstract method will become an abstract class.

Now there is a lot more we could go into depth to include constructors and how those are implemented but I will go over that more in a future post.

Top comments (0)