top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Abstraction in Java

Introduction

Abstraction is a fundamental concept in object-oriented programming (OOP) that allows us to create complex systems by focusing on essential details and hiding unnecessary complexity.

Abstraction in Java plays a crucial role in designing robust and flexible applications. It enables developers to build a clear separation between the implementation details of a class and its external interface, making the code more manageable and easier to maintain.

Overview

This tutorial will guide you through the concept of data abstraction in Java, explaining its use case. It will even cover concepts like interface in Java, abstract class in Java, abstract method in Java and more. 

Abstraction in Java   

Abstraction in Java is a fundamental concept of object-oriented programming (OOP) that enables developers to create simplified models of real-world entities. Abstraction is achieved in Java through the use of abstract classes and interfaces, which provide a blueprint for derived classes to follow.

What is Abstract Class?

An abstract class in Java is a class that cannot be instantiated on its own but serves as a blueprint for other classes. It allows you to define common methods, fields, and behavior that can be shared by multiple subclasses. 

Abstract classes may contain both regular and abstract methods, where the latter are declared but not implemented in the abstract class itself. Subclasses must implement these abstract methods to provide their own implementation. 

An abstract class in Java provide a level of abstraction, allowing for code reuse and promoting a hierarchical structure among related classes.

Example:

abstract class Shape {
    private String color;

    public Shape(String color) {
        this.color = color;
    }

    public abstract double area();  // Abstract method

    public void display() {
        System.out.println("Color: " + color);
    }
}

class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    public double area() {
        return Math.PI * radius * radius;
    }
}

public class upGradTutorialsAbstractClass {
    public static void main(String[] args) {
        Circle circle = new Circle("Red", 5.0);
        circle.display();
        System.out.println("Area: " + circle.area());
    }
}

In the above example, we have an abstract class Shape that contains one abstract method area() and a non-abstract method display(). The Shape class is marked as abstract using the abstract keyword. The area() method is declared as abstract without any implementation. The display() method has an implementation and can be called directly.

The Circle class extends the Shape class and provides an implementation for the area() method. It also has its own additional fields and methods.

In the upGradTutorialsAbstractClass class, we create an object of Circle and call the display() method to print the color of the circle. We also call the area() method to calculate and print the area of the circle.

What is an Abstract Method?   

An abstract method in Java is a method declared in an abstract class or interface that does not have an implementation in the class or interface where it is declared. It serves as a placeholder for a method that must be implemented in the subclasses or implementing classes. 

Abstract methods are meant to be overridden by the subclasses to provide their own implementation. They define the contract or behavior that the subclasses must adhere to. 

An abstract method in Java is denoted by the "abstract" keyword and does not have a body, only the method signature.

Example:

abstract class Vehicle {
    public abstract void start();  // Abstract method
}

class Car extends Vehicle {
    public void start() {
        System.out.println("Car started");
    }
}

public class upGradTutorialsAbstractMethod {
    public static void main(String[] args) {
        Car car = new Car();
        car.start();
    }
}

In the above example, we have an abstract class Vehicle that contains one abstract method start(). The start() method is declared as abstract without any implementation.

The Car class extends the Vehicle class and provides an implementation for the start() method.

In the upGradTutorialsAbstractMethod class, we create an object of Car and call the start() method to start the car. Since the start() method is implemented in the Car class, it can be called directly.

Interface in Java

An interface in Java serves as a blueprint for classes that defines a set of methods and constants. Implementing interfaces provides a way to achieve abstraction in Java programming as well as promote loose coupling, and more.

Example:

// Interface for Shape
interface Shape {
    void draw();
    double calculateArea();
}

// Concrete class implementing the Shape interface
class Circle implements Shape {
    private double radius;

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

public void draw() {
        System.out.println("Drawing a circle");
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

// Concrete class implementing the Shape interface
class Rectangle implements Shape {
    private double length;
    private double width;

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

    public void draw() {
        System.out.println("Drawing a rectangle");
    }

    public double calculateArea() {
        return length * width;
    }
}

// Main class
public class upGradTutorials {
    public static void main(String[] args) {
        Circle circle = new Circle(5.0);
        circle.draw();
        System.out.println("Area of circle: " + circle.calculateArea());

        Rectangle rectangle = new Rectangle(4.0, 6.0);
        rectangle.draw();
        System.out.println("Area of rectangle: " + rectangle.calculateArea());
    }
}

In the above example, we have an interface called Shape which defines two methods: draw() and calculateArea(). The draw() method is responsible for drawing the shape, and the calculateArea() method calculates the area of the shape.

The Circle class and Rectangle class are concrete classes that implement the Shape interface. They provide their own implementations for the draw() and calculateArea() methods.

Why do Classes Have to Implement Interfaces?   

Classes in Java implement interfaces to fulfill a specific set of requirements. By implementing an interface, a class promises to provide certain methods or behavior defined by the interface. 

This allows objects of that class to be treated as instances of the interface, promoting code organization and reusability and ensuring consistent behavior across different classes.

Which Classes Should Implement Interfaces?  

In Java, any class can implement an interface. Implementing an interface is a way to ensure that a class adheres to a contract and provides the necessary methods and behavior defined by the interface. 

Abstract Class Having Constructor, Data member and Methods

// Abstract class Shape
abstract class Shape {
    protected String color;

    // Constructor
    public Shape(String color) {
        this.color = color;
    }

    // Abstract method
    public abstract double calculateArea();


    // Concrete method
    public void display() {
        System.out.println("This is a " + color + " shape.");
    }
}

// Concrete subclass Circle
class Circle extends Shape {
    private double radius;


    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

// Concrete subclass Rectangle
class Rectangle extends Shape {
    private double length;
    private double width;

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

    public double calculateArea() {
        return length * width;
    }
}

// Main class
public class upGradTutorials {
    public static void main(String[] args) {
        Circle circle = new Circle("Red", 5.0);
        circle.display();
        System.out.println("Area of circle: " + circle.calculateArea());


        Rectangle rectangle = new Rectangle("Blue", 4.0, 6.0);
        rectangle.display();
        System.out.println("Area of rectangle: " + rectangle.calculateArea());
    }
}

In the above example, we have an abstract class called Shape. It has a constructor that takes a color parameter and initializes the color data member. The class also has an abstract method calculateArea() that needs to be implemented by its concrete subclasses.

The Circle and Rectangle classes are concrete subclasses of Shape. They provide their own implementations for the calculateArea() method, and they also invoke the constructor of the Shape class using the super keyword.

Algorithm to Implement Abstraction in Java

We can follow the following algorithm to implement abstraction in Java:

  • Identify the common characteristics and behaviors that the related classes should have.

  • Create an abstract class to represent the common characteristics and behaviors. Declare the class using the abstract keyword.

  • Define data members and methods in the abstract class that are common to the related classes.

  • Identify the methods that should be implemented differently by the related classes. Declare those methods as abstract methods by omitting the implementation.

  • Provide concrete implementations for the common methods in the abstract class.

  • Create concrete subclasses by extending the abstract class. Implement the abstract methods in the subclasses.

  • Use the concrete subclasses to create objects and invoke methods.

When to Use Abstract Classes and Abstract Methods?

Abstract classes are used when you want to define a common blueprint for a group of related classes. They allow you to share attributes and methods among subclasses and enforce a structure or hierarchy. Abstract methods are used when you want to define a method in an abstract class or interface without implementing it.

Why do we Use Abstraction?   

Abstraction in Java, specifically abstract classes and abstract methods, are used to create a blueprint for related classes and enforce common behavior. Abstract classes provide a way to share attributes and methods among subclasses, while abstract methods ensure that subclasses provide their own implementation. 

Abstraction promotes code reusability, modularity, and contract adherence, allowing for more flexible and maintainable code.

Encapsulation vs Data Abstraction   

The key differences between encapsulation and data abstraction in Java have been illustrated in the table below:

Advantages of Abstraction

The advantages of abstraction in Java include:

  • Simplified code complexity by hiding implementation details.

  • Enhances code reusability and maintainability through abstract classes and interfaces.

  • Facilitates modular design and promotes loose coupling between components.

  • Provides a clear and concise interface for interacting with complex systems.

Disadvantages of Abstraction 

Abstraction in Java has the following disadvantages:-

  • Abstraction can introduce additional complexity, making the code harder to understand and debug.

  • Abstraction may add overhead in terms of performance leading to a slight decrease in efficiency.

  • Understanding and working with abstract concepts and interfaces may require a steeper learning curve for developers.

Example of Data Abstraction

// Step 1: Identify the common characteristics and behaviors
// related to vehicles
// Step 2: Create an abstract class
abstract class Vehicle {
    // Step 3: Define data members and common methods
    protected String brand;
    protected String color;


    public Vehicle(String brand, String color) {
        this.brand = brand;
        this.color = color;
    }


    // Step 4: Declare abstract methods
    public abstract void start();


    public abstract void stop();
}


// Step 6: Create concrete subclasses
class Car extends Vehicle {
    public Car(String brand, String color) {
        super(brand, color);
    }


    // Step 4: Implement abstract methods
    public void start() {
        System.out.println(color + " " + brand + " car is starting");
    }


    public void stop() {
        System.out.println(color + " " + brand + " car is stopping");
    }
}


class Bike extends Vehicle {
    public Bike(String brand, String color) {
        super(brand, color);
    }


    // Step 4: Implement abstract methods
    public void start() {
        System.out.println(color + " " + brand + " bike is starting");
    }


    public void stop() {
        System.out.println(color + " " + brand + " bike is stopping");
    }
}


// Step 7: Use the concrete subclasses
public class upGradTutorials {
    public static void main(String[] args) {
        Vehicle car = new Car("Honda", "Red");
        car.start();
        car.stop();


        Vehicle bike = new Bike("Yamaha", "Blue");
        bike.start();
        bike.stop();
    }
}

Conclusion

Abstraction in Java programming helps developers simplify complex systems by focusing on important details and hiding unnecessary complexity. Hence, understanding and using it allows developers to write better code that is more flexible and easier to work with. To hone your skills in Java programming, consider joining a professional course offered by upGrad. 

FAQs

1. Why is an abstract class used in Java?

Abstract classes are used in Java to provide a common blueprint for related classes, promoting code reusability and defining common behavior.

2. How many types of abstraction are there in Java?

In Java, there are two types of abstraction: abstraction through abstract classes and abstraction through interfaces.

3. What does abstract class in OOP mean?

In OOP, an abstract class is a blueprint for other classes, providing shared attributes and behaviors that cannot be directly instantiated.

Leave a Reply

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