Abstraction in Java with Example


1. Overview

In this article, we will learn the important object-oriented concept - Abstraction.
Abstraction means hiding lower-level details and exposing only the essential and relevant details to the users. In this post, we will learn Abstraction concept in detail with examples.


2. Intent/Definition

Abstraction means hiding lower-level details and exposing only the essential and relevant details to the users.

Real world example

  1. The first example, let's consider a Car, which abstracts the internal details and exposes to the driver only those details that are relevant to the interaction of the driver with the Car.
  2. The second example, consider an ATM Machine; All are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statement…etc. but we can't know internal details about ATM.
  3. The third example, we never buy a "device", but always buy something more specific: iPhone, GSII, Nokia 3310 etc Here, iPhone, GSII, and N3310 are concrete things, the device is abstract.

3. Implementation

In Java, abstraction is achieved by Interfaces and Abstract classes. We can achieve 100% abstraction using Interfaces.
Let's understand Abstraction concept with Java programming examples.

Example 1: Employee, Contractor, and FullTimeEmployee Example

In this example, we create an abstract Employee class and which contains abstract calculateSalary() method. Let the subclasses extend Employee class and implement a calculateSalary() method.

Let's create Contractor and FullTimeEmployee classes as we know that the salary structure for a contractor and full-time employees are different so let these classes to override and implement a calculateSalary() method.

Let's write source code by looking into an above class diagram.
Step 1: Let's first create the superclass Employee. Note the usage of abstract keyword in this class definition. This marks the class to be abstract, which means it can not be instantiated directly. We define a method called calculateSalary() as an abstract method. This way you leave the implementation of this method to the inheritors of the Employee class.
public abstract class Employee {

    private String name;
    private int paymentPerHour;

    public Employee(String name, int paymentPerHour) {
        this.name = name;
        this.paymentPerHour = paymentPerHour;
    }

    public abstract int calculateSalary();
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPaymentPerHour() {
        return paymentPerHour;
    }
    public void setPaymentPerHour(int paymentPerHour) {
        this.paymentPerHour = paymentPerHour;
    }
}
Step 2: The Contractor class inherits all properties from its parent abstract Employee class but have to provide its own implementation to calculateSalary() method. In this case, we multiply the value of payment per hour with given working hours.
public class Contractor extends Employee {

    private int workingHours;
    public Contractor(String name, int paymentPerHour, int workingHours) {
        super(name, paymentPerHour);
        this.workingHours = workingHours;
    }
    @Override
    public int calculateSalary() {
        return getPaymentPerHour() * workingHours;
    }
}
Step 3: The FullTimeEmployee also has its own implementation of calculateSalary() method. In this case, we just multiply by a constant value of 8 hours.
public class FullTimeEmployee extends Employee {
    public FullTimeEmployee(String name, int paymentPerHour) {
        super(name, paymentPerHour);
    }
    @Override
    public int calculateSalary() {
        return getPaymentPerHour() * 8;
    }
}
Step 4: Let's create a AbstractionDemo class to test implementation of Abstraction with below code:
public class AbstractionDemo {

    public static void main(String[] args) {

        Employee contractor = new Contractor("contractor", 10, 10);
        Employee fullTimeEmployee = new FullTimeEmployee("full time employee", 8);
        System.out.println(contractor.calculateSalary());
        System.out.println(fullTimeEmployee.calculateSalary());
    }
}

Example 2: Drawing Shapes Example

Consider the second example Shapes base type is “shape” and each shape has a color, size and so on. From this, specific types of shapes are derived(inherited)-circle, square, triangle and so on.
The area for these shapes are different so make the area() method abstract and let the subclasses to override and implement.
abstract class Shape {
    String color;

    // these are abstract methods
    abstract double area();

    public abstract String toString();

    // abstract class can have constructor
    public Shape(String color) {
        System.out.println("Shape constructor called");
        this.color = color;
    }

    // this is a concrete method
    public String getColor() {
        return color;
    }
}

class Circle extends Shape {
    double radius;

    public Circle(String color, double radius) {

        // calling Shape constructor
        super(color);
        System.out.println("Circle constructor called");
        this.radius = radius;
    }

    @Override
    double area() {
        return Math.PI * Math.pow(radius, 2);
    }

    @Override
    public String toString() {
        return "Circle color is " + super.color + "and area is : " + area();
    }

}

class Rectangle extends Shape {

    double length;
    double width;

    public Rectangle(String color, double length, double width) {
        // calling Shape constructor
        super(color);
        System.out.println("Rectangle constructor called");
        this.length = length;
        this.width = width;
    }

    @Override
    double area() {
        return length * width;
    }

    @Override
    public String toString() {
        return "Rectangle color is " + super.color + "and area is : " + area();
    }

}

public class AbstractionTest {
    public static void main(String[] args) {
        Shape s1 = new Circle("Red", 2.2);
        Shape s2 = new Rectangle("Yellow", 2, 4);

        System.out.println(s1.toString());
        System.out.println(s2.toString());
    }
}

Key Points about Abstract classes and Abstract methods

  • An abstract class is a class that is declared with abstract keyword.
  • An abstract method is a method that is declared without an implementation.
  • An abstract class may or may not have all abstract methods. Some of them can be concrete methods
  • A method defined abstract must always be redefined in the subclass, thus making overriding compulsory OR either make subclass itself abstract.
  • Any class that contains one or more abstract methods must also be declared with abstract keyword.
  • There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.
  • An abstract class can have parameterized constructors and default constructor is always present in an abstract class.
Read more about Abstract class with examples at What is Abstract Class and Abstract Method in Java with Examples

GitHub Repository

 The source code of this article available on my GitHub repository at OOPS Concepts Tutorial.
If you like this article then give a star to this repository.

Learn complete Java Programming with Examples

  1. Java Tutorial for Beginners
  2. 50 Java Keywords
  3. JDBC 4.2 Tutorial
  4. All Java/J2EE Tutorial
  5. Java 8 Tutorial
  6. Java Collections Tutorial
  7. Java Exceptions Tutorial
  8. Java Generics Tutorial
  9. Java 8 Stream API Tutorial
  10. Java Wrapper Classes
  11. Java Arrays Guide
  12. Java Multithreading Tutorial
  13. Java Concurrency Tutorial
  14. Oops Concepts Tutorial
  15. Java String API Guide
  16. Java Reflection API Tutorial
  17. Java I/O Tutorial
  18. Date and Time API Tutorial
  19. JUnit 5 Tutorial
  20. JUnit 4 Tutorial
  21. Java XML Tutorial
  22. Google GSON Tutorial

Top Java EE Tutorials

  1. Spring Security Tutorial
  2. RabbitMQ Tutorial
  3. Hibernate ORM 5
  4. Java Persistence API
  5. Spring Boot 2 Tutorial
  6. Spring Core 5 Tutorial
  7. Spring MVC 5 Tutorial
  8. Spring Data JPA Tutorial
  9. Apache HttpClient Tutorial
  10. Spring Framework 5
  11. Apache Maven Tutorial
  12. JAX-RS Tutorial
  13. Jersey Rest Tutorial

Java Library Tutorials

  1. Java API Guides
  2. Java SQL Package Tutorial
  3. All Java/J2EE Tutorial
  4. Java Lang Package Tutorial
  5. Java Util Package Tutorial
  6. Java Lang Reflect Package Tutorial
  7. Java Time Package Tutorial
  8. Java IO Package Tutorial

Top Java Best Practices

  1. Java Enums and Annotations Best Practices
  2. Java Generics Best Practices
  3. JUnit Framework Best Practices
  4. Java Naming Conventions
  5. Single Responsibility Principle
  6. Liskov's Substitution Principle
  7. Interface Segregation Principle
  8. Dependency Inversion Principle
  9. Open Closed Principle
  10. Oops principles in java
  11. Restful API Best Practices
  12. JSP Best Practices
  13. Guide to JDBC Best Practices
  14. Collection Best Practices
  15. String Best Practices in Java
  16. Exception Handling Best Practices
  17. Synchronization Best Practices
  18. Guide to JDBC Best Practices
  19. Serialization Best Practices




< Previous Next >

OOPS Tutorial


Comments

  1. Examples are very good with explanation.

    ReplyDelete
  2. Very well described Abstraction concept with lots of examples. Other OOPS concepts are very well explained. Keep helping thanks

    ReplyDelete
  3. Very nicely explained OOPS concepts.

    ReplyDelete

Post a Comment