Abstraction in Java

Last Updated : 04 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Abstraction in Java is the process in which we only show essential details/functionality to the user. The non-essential implementation details are not displayed to the user. 

In this article, we will learn about abstraction and what abstraction means.

Simple Example to understand Abstraction:

Television remote control is an excellent example of abstraction. It simplifies the interaction with a TV by hiding the complexity behind simple buttons and symbols, making it easy without needing to understand the technical details of how the TV functions.

What is Abstraction in Java?

In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.

Data Abstraction may also be defined as the process of identifying only the required characteristics of an object ignoring the irrelevant details. The properties and behaviors of an object differentiate it from other objects of similar type and also help in classifying/grouping the objects.

Abstraction Real-Life Example:

Consider a real-life example of a man driving a car. The man only knows that pressing the accelerator will increase the speed of a car or applying brakes will stop the car, but he does not know how on pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc. in the car. This is what abstraction is. 

Java Abstract classes and Java Abstract methods

  1. An abstract class is a class that is declared with an abstract keyword.
  2. An abstract method is a method that is declared without implementation.
  3. An abstract class may or may not have all abstract methods. Some of them can be concrete methods
  4. A abstract method must always be redefined in the subclass, thus making overriding compulsory or making the subclass itself abstract.
  5. Any class that contains one or more abstract methods must also be declared with an abstract keyword.
  6. There can be no object of an abstract class. That is, an abstract class can not be directly instantiated with the new operator.
  7. An abstract class can have parameterized constructors and the default constructor is always present in an abstract class.

Algorithm to implement abstraction in Java

  1.  Determine the classes or interfaces that will be part of the abstraction.
  2. Create an abstract class or interface that defines the common behaviors and properties of these classes.
  3. Define abstract methods within the abstract class or interface that do not have any implementation details.
  4. Implement concrete classes that extend the abstract class or implement the interface.
  5. Override the abstract methods in the concrete classes to provide their specific implementations.
  6. Use the concrete classes to contain the program logic.

When to use abstract classes and abstract methods?

There are situations in which we will want to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. Sometimes we will want to create a superclass that only defines a generalization form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.

Consider a classic “shape” example, perhaps used in a computer-aided design system or game simulation. The 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 — each of which may have additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors may be different, such as when you want to calculate the area of a shape. The type hierarchy embodies both the similarities and differences between the shapes.

Abstract Class in Java

Java Abstraction Example

Example 1:

Java
// Java program to illustrate the
// concept of Abstraction
abstract class Shape {
    String color;

    // these are abstract methods
    abstract double area();
    public abstract String toString();

    // abstract class can have the 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.getColor()
            + "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.getColor()
            + "and area is : " + area();
    }
}
public class Test {
    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());
    }
}

Output
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0

Example 2:

Java
// Java Program to implement
// Java Abstraction

// Abstract Class declared
abstract class Animal {
    private String name;

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

    public abstract void makeSound();

    public String getName() { return name; }
}

// Abstracted class
class Dog extends Animal {
    public Dog(String name) { super(name); }

    public void makeSound()
    {
        System.out.println(getName() + " barks");
    }
}

// Abstracted class
class Cat extends Animal {
    public Cat(String name) { super(name); }

    public void makeSound()
    {
        System.out.println(getName() + " meows");
    }
}

// Driver Class
public class AbstractionExample {
    // Main Function
    public static void main(String[] args)
    {
        Animal myDog = new Dog("Buddy");
        Animal myCat = new Cat("Fluffy");

        myDog.makeSound();
        myCat.makeSound();
    }
}

Output
Buddy barks
Fluffy meows

Explanation of the above Java program:

This code defines an Animal abstract class with an abstract method makeSound(). The Dog and Cat classes extend Animal and implement the makeSound() method. The main() method creates instances of Dog and Cat and calls the makeSound() method on them. 

This demonstrates the abstraction concept in Java, where we define a template for a class (in this case Animal), but leave the implementation of certain methods to be defined by subclasses (in this case makeSound()).

Interface

Interfaces are another method of implementing abstraction in Java. The key difference is that, by using interfaces, we can achieve 100% abstraction in Java classes. In Java or any other language, interfaces include both methods and variables but lack a method body. Apart from abstraction, interfaces can also be used to implement inheritance in Java.

Implementation: To implement an interface we use the keyword “implements” with class.

Java
// Define an interface named Shape
interface Shape {
    double calculateArea(); // Abstract method for
                            // calculating the area
}

// Implement the interface in a class named Circle
class Circle implements Shape {
    private double radius;

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

    // Implementing the abstract method from the Shape
    // interface
    public double calculateArea()
    {
        return Math.PI * radius * radius;
    }
}

// Implement the interface in a class named Rectangle
class Rectangle implements Shape {
    private double length;
    private double width;

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

    // Implementing the abstract method from the Shape
    // interface
    public double calculateArea() { return length * width; }
}

// Main class to test the program
public class Main {
    public static void main(String[] args)
    {
        // Creating instances of Circle and Rectangle
        Circle myCircle = new Circle(5.0);
        Rectangle myRectangle = new Rectangle(4.0, 6.0);

        // Calculating and printing the areas
        System.out.println("Area of Circle: "
                           + myCircle.calculateArea());
        System.out.println("Area of Rectangle: "
                           + myRectangle.calculateArea());
    }
}

Output
Area of Circle: 78.53981633974483
Area of Rectangle: 24.0

Advantages of Abstraction

Here are some advantages of abstraction:

  • It reduces the complexity of viewing things.
  • Avoids code duplication and increases reusability.
  • Helps to increase the security of an application or program as only essential details are provided to the user.
  • It improves the maintainability of the application. 
  • It improves the modularity of the application. 
  • The enhancement will become very easy because without affecting end-users we can able to perform any type of changes in our internal system. 
  • Improves code reusability and maintainability.
  • Hides implementation details and exposes only relevant information.
  • Provides a clear and simple interface to the user.
  • Increases security by preventing access to internal class details.
  • Supports modularity, as complex systems can be divided into smaller and more manageable parts.
  • Abstraction provides a way to hide the complexity of implementation details from the user, making it easier to understand and use.
  • Abstraction allows for flexibility in the implementation of a program, as changes to the underlying implementation details can be made without affecting the user-facing interface.
  • Abstraction enables modularity and separation of concerns, making code more maintainable and easier to debug.

Disadvantages of Abstraction in Java

Here are the main disadvantages of abstraction in Java:

  • Abstraction can make it more difficult to understand how the system works.
  • It can lead to increased complexity, especially if not used properly.
  • This may limit the flexibility of the implementation.
  • Abstraction can add unnecessary complexity to code if not used appropriately, leading to increased development time and effort.
  • Abstraction can make it harder to debug and understand code, particularly for those unfamiliar with the abstraction layers and implementation details.
  • Overuse of abstraction can result in decreased performance due to the additional layers of code and indirection.

Also Read:

Abstraction in Java – FAQs

Why do we use abstract?

One key reason we use abstract concepts is to simplify complexity. Imagine trying to explain the entire universe with every single atom and star! Abstracts let us zoom out, grab the main ideas like gravity and energy, and make sense of it all without getting lost in the details.

Here are some other reasons why we use abstract in Java:

1. Abstraction: Abstract classes are used to define a generic template for other classes to follow. They define a set of rules and guidelines that their subclasses must follow. By providing an abstract class, we can ensure that the classes that extend it have a consistent structure and behavior. This makes the code more organized and easier to maintain.

2. Polymorphism: Abstract classes and methods enable polymorphism in Java. Polymorphism is the ability of an object to take on many forms. This means that a variable of an abstract type can hold objects of any concrete subclass of that abstract class. This makes the code more flexible and adaptable to different situations.

3. Frameworks and APIs: Java has numerous frameworks and APIs that use abstract classes. By using abstract classes developers can save time and effort by building on existing code and focusing on the aspects specific to their applications.

What is the Difference between Encapsulation and Data Abstraction?

Here are some key difference b/w encapsulation and abstraction:

Encapsulation

Abstraction

Encapsulation is data hiding(information hiding)Abstraction is detailed hiding(implementation hiding).
Encapsulation groups together data and methods that act upon the dataData Abstraction deals with exposing the interface to the user and hiding the details of implementation
Encapsulated classes are Java classes that follow data hiding and abstractionImplementation of abstraction is done using abstract classes and interface
Encapsulation is a procedure that takes place at the implementation levelabstraction is a design-level process

What is a real-life example of data abstraction?

Television remote control is an excellent real-life example of abstraction. It simplifies the interaction with a TV by hiding the complexity behind simple buttons and symbols, making it easy without needing to understand the technical details of how the TV functions.

What is the Difference between Abstract Classes and Interfaces in Java?

Here are some key difference b/w Abstract Classes and Interfaces in Java:

Abstract Class

Interfaces

Abstract classes support abstract and Non-abstract methods.Interface in Java can have abstract methods, default methods, and static methods.
Doesn’t support Multiple Inheritance.Supports Multiple Inheritance.
Abstract classes can be extended by Java classes and multiple interfacesThe interface can be extended by Java interface only.
Abstract class members in Java can be private, protected, etc.Interfaces are public by default.

Example:

public abstract class Vehicle{
public abstract void drive()
}

Example:

public interface Animal{
void speak();
}



Previous Article
Next Article

Similar Reads

Abstraction by Parameterization and Specification in Java
Abstraction by Parameterization and specification both are important methods in Java. We do this in hope of simplifying our analysis by separating attributes and details implementation for user requirements by showing the essential part to the user and hiding certain details for various purposes like security, maintenance, etc. Abstractions help us
4 min read
Difference Between Data Hiding and Abstraction in Java
Abstraction Is hiding the internal implementation and just highlight the set of services. It is achieved by using the abstract class and interfaces and further implementing the same. Only necessarily characteristics of an object that differentiates it from all other objects. Only the important details are emphasized and the rest all are suppressed
6 min read
Control Abstraction in Java with Examples
Our aim is to understand and implement Control Abstraction in Java. Before jumping right into control abstraction, let us understand what is abstraction. Abstraction: To put it in simple terms, abstraction is nothing but displaying only the essential features of a system to a user without getting into its details. For example, a car and its functio
3 min read
Difference between Abstraction and Encapsulation in Java with Examples
Abstraction and Encapsulation are two of the fundamental concepts in Object-Oriented-Programming. They provide features such as code-reusability, overriding, security purpose, data hiding, and implementation hiding, which help to make the program easy to understand, maintain and secure. However, it can be quite confusing for a beginner to understan
6 min read
Understanding OOPs and Abstraction using Real World Scenario
Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. In this article, we will discuss how this OOP's concept is implemented in real world
4 min read
Understanding Encapsulation, Inheritance, Polymorphism, Abstraction in OOPs
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of t
6 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Java.math.BigInteger.modInverse() method in Java
Prerequisite : BigInteger Basics The modInverse() method returns modular multiplicative inverse of this, mod m. This method throws an ArithmeticException if m <= 0 or this has no multiplicative inverse mod m (i.e., gcd(this, m) != 1). Syntax: public BigInteger modInverse(BigInteger m) Parameters: m - the modulus. Return Value: This method return
2 min read
Java.math.BigInteger.probablePrime() method in Java
Prerequisite : BigInteger Basics The probablePrime() method will return a Biginteger of bitLength bits which is prime. bitLength is provided as parameter to method probablePrime() and method will return a prime BigInteger of bitLength bits. The probability that a BigInteger returned by this method is composite and does not exceed 2^-100. Syntax: pu
2 min read
Java | How to start learning Java
Java is one of the most popular and widely used programming languages and platforms. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable, and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in
5 min read
Java Stream | Collectors toCollection() in Java
Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed. Syntax: public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supp
2 min read
three90RightbarBannerImg