Abstraction Program in Java (with a Real Time Example)

Abstraction in Java basically means filtering out all the noise so we can concentrate on what matters. It is kind of like driving a car you don’t have to know the detailed workings of every piece of the engine; you just have to know how to drive. So, in Java, abstraction works pretty much the same way. It lets you focus on “what” rather than “how.” Let’s go deep on abstraction using real-world examples and code snippets with the purpose of making the abstraction concept come alive.

Real-Time Example: Vehicle Abstraction in Java

Imagine you’re writing an application for a ride-sharing program. You’re going to handle all kinds of vehicles, let’s say cars, bikes, and buses. But you don’t care about those specific details, but rather that the vehicle has to perform the basic operation: start the vehicle, then stop it and accelerate it. That’s where abstraction is applicable.

Abstraction in Java

Here’s how you can represent this idea in Java using abstract classes:

// Abstract class for Vehicle
abstract class Vehicle {
    abstract void start();
    abstract void stop();
}

// Car class that extends Vehicle
class Car extends Vehicle {
    void start() {
        System.out.println("Car starts with a key.");
    }
    void stop() {
        System.out.println("Car stops with brakes.");
    }
}

// Bike class that extends Vehicle
class Bike extends Vehicle {
    void start() {
        System.out.println("Bike starts with a kick.");
    }
    void stop() {
        System.out.println("Bike stops with hand brakes.");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle myCar = new Car();
        myCar.start();  // Output: Car starts with a key.
        myCar.stop();   // Output: Car stops with brakes.

        Vehicle myBike = new Bike();
        myBike.start();  // Output: Bike starts with a kick.
        myBike.stop();   // Output: Bike stops with hand brakes.
    }
}

In this program, the Vehicle class is abstract and it doesn’t need to care about how each type of vehicle starts or stops. It just declares that every vehicle must have these capabilities, and the specific vehicle types (Car and Bike) implement the details.

Java Abstract Classes and Methods

Abstract Classes

In Java, an abstract class is a class that cannot be instantiated. It serves as a blueprint for other classes. Think of it as a concept or a template that needs to be further developed in subclasses.

Features of Abstract Classes:

  • Partial abstraction: Abstract classes may contain both abstract methods (methods without a body) and concrete methods (fully implemented methods).
  • Reusability: Common logic can be shared among multiple classes through inheritance.
  • Inheritance: Other classes can extend the abstract class and provide implementations for its abstract methods.

Abstract Methods

An abstract method is a method that does not have a body. It must be implemented in a subclass.

Syntax:

abstract class MyClass {
    abstract void myMethod(); // Abstract method
}

Subclasses must override these methods to provide their specific behavior.

Ways to Achieve Abstraction in Java

Java offers two ways to achieve abstraction:

  1. Abstract classes (as shown in the previous example)
  2. Interfaces (which we’ll talk about shortly)
Advantages of Abstraction in Java

Procedure to Achieve Abstraction

  1. Create an abstract class or interface.
  2. Declare abstract methods inside the abstract class or interface.
  3. Extend the abstract class or implement the interface in your concrete class.
  4. Provide specific implementations for the abstract methods.

Rules for Declaring Abstract Classes in Java

  • An abstract class must be declared with the keyword abstract.
  • If a class has at least one abstract method, the class itself must be declared abstract.
  • Abstract classes cannot be instantiated.
  • If a subclass does not implement all abstract methods from its parent class, it must also be declared as abstract.

Example of Abstraction in Java

abstract class Animal {
    abstract void sound();
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

In Java, abstraction can simplify algorithms by allowing you to concentrate on the essential logic without getting caught up in the specifics of implementation. For example, when dealing with sorting algorithms, you can use abstraction to outline the general idea of sorting while delegating the specific implementations, like the Quick Sort Algorithm Complexity or the Bubble Sort algorithm, to the concrete classes. This approach aids in handling complex algorithms with cleaner and more organized code.

Interface vs. Abstract Class: Key Differences

When should you use an abstract class, and when should you use an interface? Good question!

Interface:

  • Full abstraction: Only abstract methods are allowed (Java 7 and earlier). However, since Java 8, interfaces can have default and static methods.
  • Multiple inheritance: A class can implement multiple interfaces, providing flexibility.
  • Fields: By default, fields in an interface are public, static, and final.

Abstract Class:

  • Partial abstraction: Can contain both abstract and concrete methods.
  • Single inheritance: A class can extend only one abstract class.
  • Fields: An abstract class can have any type of field (public, private, protected).

Syntax: Interface vs Abstract Class in Java

Abstract Class Syntax

abstract class AbstractClass {
    abstract void abstractMethod();
    void concreteMethod() {
        // concrete method
    }
}

Interface Syntax

interface MyInterface {
    void method1();
}

When to Use What?

  • Use abstract classes when you want to share code among closely related classes.
  • Use interfaces when you expect different classes to implement the same set of methods but they don’t necessarily share a common ancestor.

Advantages of Abstraction in Java

  • Code simplicity: Focus on the essentials. You don’t have to worry about unnecessary details.
  • Flexibility: Abstract classes allow for flexibility in how methods are implemented in subclasses.
  • Code reusability: Abstract classes can be used to define common behavior that can be shared across subclasses.

Disadvantages of Abstraction in Java

  • Complexity: Sometimes, abstraction can lead to more complex designs, especially when multiple layers of inheritance are involved.
  • Less flexibility with single inheritance: Since a class can only extend one abstract class, it limits the ability to mix functionalities from multiple sources.

Encapsulation vs Abstraction

While abstraction hides the complexity of how something works, encapsulation hides the data itself, controlling access through getters and setters. Think of abstraction as focusing on “what” a class does, while encapsulation ensures the “how” (data and its manipulation) stays safe and controlled.


Conclusion

Abstraction in Java is one of the basic concepts of simplifying complex systems and exposing only details that are relevant. Powerful tools for implementing abstraction in Java are found with or without interfaces or abstract classes; your code will be even more modular, flexible, and maintainable. Now, go ahead and build your own abstractions- you’ve got this!

Scroll to Top