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:


Advanced Abstraction: Constructors, Static, and Final Methods

Even though you cannot instantiate an abstract class directly using the new keyword, an abstract class can still have a constructor. This constructor is called when a subclass is instantiated (usually implicitly, or explicitly via super()).

Abstract classes can also contain:

Advanced Abstract Class Example

abstract class Vehicle {
  String type;

// Constructor in an abstract class public Vehicle(String type) { this.type = type; System.out.println("Vehicle constructor called. Type: " + type); }

// Abstract method public abstract void startEngine();

// Final method (cannot be overridden) public final void stopEngine() { System.out.println("Engine stopped safely."); }

// Static method public static void serviceRoutine() { System.out.println("Perform standard 10,000 mile service."); } }

class Car extends Vehicle { public Car() { // Calling the abstract class constructor super("Car"); }

@Override public void startEngine() { System.out.println("Car engine starting: Vroom!"); } }

public class Main { public static void main(String[] args) { Vehicle.serviceRoutine(); // Call static method directly Car myCar = new Car(); // Triggers the Vehicle constructor myCar.startEngine(); myCar.stopEngine(); // Using the final method } }


Exercise

?

Can you create an object of an abstract class?