Java Abstraction: A Comprehensive Guide to Abstract Classes and Methods

Learn about data abstraction in Java using abstract classes and methods. This comprehensive guide explains the abstract keyword and its role in creating flexible and reusable code.



Java Abstraction

Data abstraction hides certain details and shows only essential information. It can be achieved using abstract classes or interfaces.

Abstract Classes and Methods

Abstract classes and methods use the abstract keyword.

  • Abstract class: A restricted class that cannot be used to create objects. It must be inherited from another class.
  • Abstract method: Can only be used in an abstract class and does not have a body. The subclass provides the body.

An abstract class can have both abstract and regular methods:

Example

abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}

You cannot create an object of an abstract class:

Example

Animal myObj = new Animal(); // Error

To use an abstract class, it must be inherited. Use the extends keyword:

Example

// Abstract class
abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println("Zzz");
}
}

// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Main {
public static void main(String[] args) {
Pig myPig = new Pig();
myPig.animalSound();
myPig.sleep();
}
}
Output

The pig says: wee wee
Zzz

Why Use Abstract Classes and Methods?

  • To achieve security by hiding certain details and showing only the important parts.

Note: Abstraction can also be achieved with Interfaces, which you will learn about in the next chapter.