abstraction in java

what is abstraction in java

Here are some questions about abstraction in java which most of time asked in java interviews

  1. What is abstraction in java
  2. How we can Achieve Abstraction in Java
  3. What is difference between abstract class and interface
  4. When we use abstract class and interface in java


what is abstraction in java

Abstraction in Java is a fundamental concept in object-oriented programming that involves simplifying complex systems by modeling classes based on their essential properties and behaviors. It focuses on representing the relevant aspects of an object while hiding unnecessary details. Abstraction allows you to define the structure and behavior of a system without specifying the implementation details.

Let’s illustrate the concept of abstraction with a real-life example:

Real-life Example: Television Remote Control

Imagine you have a television remote control. The remote control serves as an abstraction of the television system. When you interact with the remote, you are using a simplified interface to control the television without needing to understand the intricate details of how the television works internally.

Here’s how this example aligns with the concept of abstraction:

1. Essential Properties: The remote control abstracts the essential properties of the television, such as changing channels, adjusting volume, and turning the power on or off.

2. Behavior: The remote control provides a high-level interface (buttons) that allows you to perform specific actions without knowing the internal workings of the television. For example, you press the “volume up” button, and the television’s volume increases.

3. Hiding Details: The internal details of how the remote control communicates with the television, the technology used for signal transmission, and the television’s circuitry are hidden from the user. The user interacts with a simplified interface that abstracts away these complexities.

4. Flexibility and Ease of Use: The abstraction provided by the remote control makes it easier for users to control the television without needing in-depth knowledge of electronics. The user can focus on the desired actions (changing channels, adjusting volume) without being concerned with the technical details.

In this real-life example, the television remote control serves as an abstraction of the television system, providing a simplified and user-friendly interface. Similarly, in software development, abstraction involves creating models (classes and interfaces) that represent the essential properties and behaviors of a system, allowing developers to work at a higher level of conceptualization and hide unnecessary implementation details.

Example# 01:

Let’s create a simple Java example to represent a television remote control and its basic functionality. In this example, we’ll focus on abstraction by creating a RemoteControl interface that abstracts the essential actions a remote control can perform.

Example
// RemoteControl interface representing the abstraction
interface RemoteControl {
    void powerOn();
    void powerOff();
    void changeChannel(int channel);
    void adjustVolume(int volume);
}

// Television class implementing the RemoteControl interface
class Television implements RemoteControl {
    private boolean isOn;
    private int currentChannel;
    private int volume;

    public Television() {
        this.isOn = false;
        this.currentChannel = 1;
        this.volume = 50;
    }

    @Override
    public void powerOn() {
        isOn = true;
        System.out.println("TV is powered on.");
    }

    @Override
    public void powerOff() {
        isOn = false;
        System.out.println("TV is powered off.");
    }

    @Override
    public void changeChannel(int channel) {
        if (isOn) {
            currentChannel = channel;
            System.out.println("Changed to channel: " + channel);
        } else {
            System.out.println("TV is not powered on.");
        }
    }

    @Override
    public void adjustVolume(int newVolume) {
        if (isOn) {
            volume = newVolume;
            System.out.println("Adjusted volume to: " + newVolume);
        } else {
            System.out.println("TV is not powered on.");
        }
    }
}

// Client code to test the television remote control
public class RemoteControlExample {
    public static void main(String[] args) {
        // Create a Television instance
        Television myTV = new Television();

        // Use the remote control interface to interact with the TV
        myTV.powerOn();
        myTV.changeChannel(5);
        myTV.adjustVolume(60);
        myTV.powerOff();
    }
}

In this example:

  • The RemoteControl interface abstracts the essential actions of a remote control: powering on/off, changing channels, and adjusting volume.
  • The Television class implements the RemoteControl interface, providing concrete implementations for each action.
  • The client code (RemoteControlExample) creates an instance of the Television class and uses the remote control interface to interact with the TV.

This example demonstrates how abstraction allows us to create a simple and consistent interface (RemoteControl) for controlling different devices without worrying about the internal details of each device. The client code interacts with the abstraction, focusing on the essential actions, and the specific implementation details of the television are encapsulated within the Television class.

Example# 02:

Let’s look at a real-life example of abstraction: a Vehicle hierarchy.

abstraction in java
Example
// Abstract class representing a general vehicle
abstract class Vehicle {
    private String model;
    private int year;

    public Vehicle(String model, int year) {
        this.model = model;
        this.year = year;
    }

    // Abstract method representing the movement of the vehicle
    public abstract void move();

    // Getter methods
    public String getModel() {
        return model;
    }

    public int getYear() {
        return year;
    }
}

// Concrete class representing a Car
class Car extends Vehicle {
    private int numberOfDoors;

    public Car(String model, int year, int numberOfDoors) {
        super(model, year);
        this.numberOfDoors = numberOfDoors;
    }

    // Implementation of the abstract method for Car
    @Override
    public void move() {
        System.out.println("The car is moving on the road.");
    }

    // Additional methods specific to Car
    public void honk() {
        System.out.println("Beep! Beep!");
    }
}

// Concrete class representing a Bicycle
class Bicycle extends Vehicle {
    private int numberOfGears;

    public Bicycle(String model, int year, int numberOfGears) {
        super(model, year);
        this.numberOfGears = numberOfGears;
    }

    // Implementation of the abstract method for Bicycle
    @Override
    public void move() {
        System.out.println("The bicycle is moving on the path.");
    }

    // Additional methods specific to Bicycle
    public void ringBell() {
        System.out.println("Ding! Ding!");
    }
}

In this example:

  • Vehicle is an abstract class that represents the concept of a generic vehicle. It has attributes like model and year, and it declares an abstract method move() representing the movement of the vehicle.
  • Car and Bicycle are concrete classes that extend Vehicle and provide specific implementations for the move() method. Each class encapsulates the details relevant to its type of vehicle.

Now, you can use abstraction to create instances of Car and Bicycle without worrying about the internal details of how they move.

For example:

Example
public class AbstractionExample {
    public static void main(String[] args) {
        // Creating instances of Car and Bicycle
        Car myCar = new Car("Sedan", 2022, 4);
        Bicycle myBicycle = new Bicycle("Mountain Bike", 2022, 21);

        // Calling the move method without knowing the specific implementation
        myCar.move();
        myBicycle.move();

        // Accessing attributes through getter methods
        System.out.println("Car Model: " + myCar.getModel());
        System.out.println("Bicycle Year: " + myBicycle.getYear());

        // Calling additional methods specific to each type of vehicle
        myCar.honk();
        myBicycle.ringBell();
    }
}

In this client code, the focus is on the high-level abstraction of a Vehicle. The specific details of how a Car or Bicycle moves are hidden behind the abstraction. This is a real-world example of abstraction, where you model the common aspects of a concept while hiding unnecessary details, allowing for flexibility and maintainability in the design of your system.


How we can Achieve Abstraction in Java

In Java, abstraction is achieved through the use of abstract classes and interfaces. Both abstract classes and interfaces allow you to declare abstract methods, which are methods without a body. Concrete classes that extend an abstract class or implement an interface must provide implementations for these abstract methods.

There are two ways to achieve abstraction in java

  1. Abstract class (0 to 100%)
  2. Interface (100%)
abstraction in java

Let’s go through examples of both abstract classes and interfaces to demonstrate how abstraction is achieved in Java:

Abstraction using Abstract Class:

Example
// Abstract class representing a shape
abstract class Shape {
    // Abstract method to calculate area
    public abstract double calculateArea();
}

// Concrete class Circle extending the abstract class
class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    // Implementation of the abstract method for Circle
    @Override
    public double calculateArea() {
        return Math.PI * Math.pow(radius, 2);
    }
}

// Concrete class Rectangle extending the abstract class
class Rectangle extends Shape {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    // Implementation of the abstract method for Rectangle
    @Override
    public double calculateArea() {
        return length * width;
    }
}

In this example, the Shape class is an abstract class that declares an abstract method calculateArea(). The Circle and Rectangle classes are concrete classes that extend the Shape abstract class and provide specific implementations for the calculateArea() method.

Abstraction using Interface:

Example
// Interface representing a printable item
interface Printable {
    void print();
}

// Concrete class implementing the interface
class Document implements Printable {
    private String content;

    public Document(String content) {
        this.content = content;
    }

    // Implementation of the interface method
    @Override
    public void print() {
        System.out.println(content);
    }
}

In this example, the Printable interface declares a single abstract method print(). The Document class implements the Printable interface, providing a specific implementation for the print() method.

This demonstrates how abstraction allows you to create a common interface for a set of related classes, promoting code reuse and providing a clear separation between interface and implementation.


What is difference between abstract class and interface

Abstract classes and interfaces are both mechanisms in Java for achieving abstraction, but they have some key differences in terms of their purpose, usage, and capabilities.

Abstract Class:

1. Purpose: An abstract class is used to provide a common base for a group of related classes. It represents a common concept or functionality shared among multiple classes.

2. Method Implementation: Abstract classes can have both abstract methods (methods without a body, declared using the abstract keyword) and concrete methods (methods with an implementation).

3. Fields (Variables): Abstract classes can have instance variables (fields) that can be inherited by their subclasses.

4. Constructors: Abstract classes can have constructors, and they are typically used to initialize the fields of the abstract class.

5. Access Modifiers: Abstract classes can have access modifiers for their methods, allowing for control over the visibility of methods in subclasses.

6. Multiple Inheritance: Java supports single inheritance, so a class can extend only one abstract class.

Interface:

1. Purpose: An interface is used to define a contract for a set of classes. It represents a set of abstract methods that any class implementing the interface must provide.

2. Method Declaration: Interfaces can only declare abstract methods (methods without a body). They do not contain method implementations.

3. Fields (Variables): Interfaces cannot have instance variables (fields). They can only have constant (static final) variables.

4. Constructors: Interfaces cannot have constructors, as they cannot be instantiated.

5. Access Modifiers: All methods in an interface are implicitly public and abstract. Fields are implicitly public, static, and final.

6. Multiple Inheritance: Java supports multiple inheritance through interfaces. A class can implement multiple interfaces.

Here’s a tabular representation of the differences between abstract classes and interfaces in Java:

FeatureAbstract ClassInterface
PurposeProvides a common base for related classes.Defines a contract for a set of classes.
Method ImplementationCan have both abstract and concrete methods.Contains only abstract methods (no body).
Fields (Variables)Can have instance variables (fields).Cannot have instance variables, only constants (static final).
ConstructorsCan have constructors.Cannot have constructors.
Access ModifiersCan have access modifiers for methods and fields.All methods are implicitly public and abstract. Fields are implicitly public, static, and final.
Multiple InheritanceSupports single inheritance.Supports multiple inheritance.
UsageUse when you want to provide common behavior and share code among related classes.Use when you want to define a contract for a set of unrelated classes or provide multiple inheritance.
InstantiationCannot be instantiated. Must be subclassed.Cannot be instantiated directly.
Use of super KeywordCan use the super keyword to call the superclass’s methods and constructor.N/A
Keyword Usedabstract class ClassName { ... }interface InterfaceName { ... }

This table summarizes the key distinctions between abstract classes and interfaces in terms of their usage, features, and capabilities. Understanding these differences helps in choosing the appropriate approach based on the requirements of your design.


when we use abstract class and interface in java

Abstract Class:

  • Use when you want to provide a common base class with some default behavior.
  • When there is a need for fields (variables) that are shared among subclasses.
  • When you need constructors in your abstraction.

Interface:

  • Use when you want to define a contract for a set of classes, irrespective of their inheritance hierarchy.
  • When multiple inheritance is needed, as a class can implement multiple interfaces.
  • When you want to achieve a form of “pure” abstraction without providing any default behavior.

Example:

Example
// Abstract class example
abstract class Animal {
    String name;

    public Animal(String name) {
        this.name = name;
    }

    abstract void makeSound();

    void eat() {
        System.out.println(name + " is eating.");
    }
}

// Interface example
interface Flyable {
    void fly();
}

class Bird extends Animal implements Flyable {
    public Bird(String name) {
        super(name);
    }

    @Override
    void makeSound() {
        System.out.println("Chirp!");
    }

    @Override
    public void fly() {
        System.out.println(name + " is flying.");
    }
}

In this example, Animal is an abstract class with a mix of abstract and concrete methods, while Flyable is an interface with only abstract methods. The Bird class extends Animal and implements Flyable, showcasing the differences between abstract classes and interfaces.

Leave a Reply

Your email address will not be published. Required fields are marked *