-
Notifications
You must be signed in to change notification settings - Fork 0
Abstract Classes
In the Inheritance you learn about inheritance and how you can use it to create specific classes from a more general class. For example, I could have a Vehicle class, a Truck class, and a Car class. The Truck class and the Car class are more specific versions of the Vehicle class. In certain cases, you may have a class that you just want to be a framework for other classes. You have no need to create objects from this class. This classes only purpose is to be a parent to other classes. This is known as a abstract class.
Creating an Abstract Class is similar to creating a regular class. The only difference is that you use the keyword abstract to signify that it is an abstract class.
public abstract class Vehicle
{
}
Above is a simple abstract method class called Vehicle. Since this is an abstract method you cannot create any objects from this method.
Just like a regular class, a regular class can have methods too. However, an abstract class can have two different types of methods. It can have nonabstract methods and abstract methods. A nonabstract method in just a regular method like you have been using up to this point. It usually has a body and can be implemented in the abstract class and inherited by the children classes. A abstract method is a method that has not a body and it must be implemented by the children of the class. Below is an example of both an abstract and nonabstract method in the vehicle class.
public abstract class Vehicle
{
private int vehicleDesc;
public abstract void year();
public String getDesc()
{
return vehicleDesc;
}
public void setDesc(String description)
{
vehicleDesc = description;
}
}
As you can see the vehicle class now has one abstract method and two regular nonabstract methods. The abstract method year will need to be set by the child classes of the Vehicle class. When you create a child class of an abstract class any abstract method must be set in the child class. So let's say you wanted to create a child class of the Vehicle class called Car.
public class Car extends Vehicle
{
@Override
public void year()
{
System.out.println("The year of this car is 2001");
}
{
Since Vehicle is an abstract class you cannot create an object of the class. However, since Car is a concrete class you can create objects from it.
Car myCar = new Car();
Now since Car is a child of the Vehicle class any object of the class can use the methods in the parent class. In this case, we will use the setDesc() and getDesc() methods from the Vehicle class. When can then output all of this information to the user in our main class.
public class UseVehicle
{
public static void main(String args[])
{
Car myCar = new Car();
myCar.setDesc("This is a nice car");
System.out.println(myCar.getDesc() + " and ");
myCar.year();
}
}
Output
This is a nice car and
The year of this car is 2001