Java Abstraction

An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon): abstract void walk();. The user will have the information on what the object does instead of how it does it.

Abstract Class

  • Abstraction is achieved using abstract classes and interfaces.
  • To use an abstract class, you have to inherit it from another class.
  • Any class that contains an abstract method should be defined as abstract.

A class containing an abstract method is an abstract class.

we can define our Animal class as abstract just like concrete class in the following way:

abstract class Animal {
  int legs = 0;
  abstract void makeSound();
}

Output

class Cat extends Animal {
  public void makeSound() {
    System.out.println("Meow");
  }
}

This is used when there is no meaningful definition for the method in the superclass.

Related Post