#
Abstract classes
In Java, abstraction is done by abstract classes and interfaces. In this tutorial we are presenting the abstract classes.
Abstraction in general hides the implementation details from the user. We can see WHAT an object can do, but not HOW.
An abstract method is a method which has only the signature. The method is not defined completely, has no body. This method has the abstract keyword before the signature.
An abstract class is a class which has one or more abstract method.
An abstract class:
- cannot be instantiated
- function as a base for other subclasses
info
- In Java an abstract class is marked using
abstractkeyword. - An abstract class can declare instance variables, with all possible access modifiers, and they can be accessed in child classes. An interface can only have public, static, and final variables (can't have any instance variables).
Here we have an example of abstract class in Java:
public abstract class Car {
public void startCar(){
System.out.println("Now we start a car");
};
abstract void buildCar();
}
This class is never instantiated, but can be used to create another class.
Supposing we need to create a VolvoCar class, a CitroenCar class, etc.
All the car classes use the same method for starting the car, but the buildCar() method is implemented differently for each car type.
We never instantiate Car class.
When we define a VolvoCar and CitroenCar classes we can use a code similar to the following code:
public class VolvoCar extends Car {
@Override
void buildCar() {
System.out.println("Implement buildCar for VolvoCar.");
}
}
public class CitroenCar extends Car {
@Override
void buildCar() {
System.out.println("Implement buildCar for CitroenCar.");
}
}
If we want to test our code, we need to create our main class:
public class MainApp {
public static void main(String [] args) {
CitroenCar citroenCar = new CitroenCar();
VolvoCar volvoCar = new VolvoCar();
citroenCar.buildCar();
citroenCar.startCar();
volvoCar.startCar();
}
}
Once we have all .java files created (in the same folder in my case) we can run javac MainApp.java in order to compile the code.
Info
We are creating the bytecode or the .class files using the javac command.
Now we can run java MainApp command in order to start the application.
