Java Abstraction

Java Abstraction

Data abstraction is the process of hiding certain details and showing only essential information to the user. Abstraction can be achieved with either abstract classes or interfaces.

The abstract keyword is a non-access modifier, used for classes and methods:


Why Use Abstract Classes and Methods?

Abstraction allows you to define a "contract" or a template for a group of subclasses. It lets you define some common behavior in the abstract class itself, while forcing subclasses to provide their own implementation for the abstract methods.

This helps to achieve security - hide certain details and only show the important details of an object.


Abstract Class Example

An abstract class can have both abstract and regular methods.

Abstract Class Example

// Abstract class
abstract class Animal {
  // Abstract method (does not have a body)
  public abstract void animalSound();
  

// Regular method public void sleep() { System.out.println("Zzz"); } }

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

class Main { public static void main(String[] args) { // Animal myObj = new Animal(); // will generate an error Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } }

In this example: