In this tutorial, we will learn about abstraction in Java. We will learn about Java abstract classes and methods and how to use them in our program.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Honda class.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output:
running safely
A method without body (no implementation) is known as abstract method. A method must always be declared in an abstract class, or in other words you can say that if a class has an abstract method, it should be declared abstract as well.
abstract class Animal {
public void displayInfo() {
System.out.println(“I am an animal.”);
}
abstract void makeSound();
}
In the above example, we have created an abstract class Animal. It contains an abstract method makeSound() and a non-abstract method displayInfo()