dsa

Java Abstract Class and Abstract Methods

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.

    The abstract keyword is a non-access modifier, used for classes and methods:
  • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
  • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).

Java Abstract Class

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
       
    Points to Remember:
  • 1.An abstract class must be declared with an abstract keyword.
  • 2.It can have abstract and non-abstract methods.
  • 3.It cannot be instantiated.
  • 4.It can have constructors and static methods also.
  • 5.It can have final methods which will force the subclass not to change the body of the method.

Java Abstract Method

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()

    Rules of Abstract Method:
  • 1. Abstract methods don’t have body, they just have method signature as shown above.
  • 2.
  • If a class has an abstract method it should be declared abstract, the vice versa is not true, which means an abstract class doesn’t need to have an abstract method compulsory.
  • 3. If a regular class extends an abstract class, then the class must have to implement all the abstract methods of abstract parent class or it has to be declared abstract as well.