How to Achieve Abstraction in Java | Real Programming Example

How to Achieve Abstraction in Java | Real Programming Example

Before proceeding to the Java programming, you should know the meaning of abstraction.

Table of Contents

What is Abstraction?

The details of what an object is doing but knowing how is being done are referred to as Abstraction.

Not clear?

In other words, the process of hiding the implementation details from the client and showing the basic functionality is an Abstraction.

It is one of the principle Object Oriented Concepts in Java.

Abstraction is accomplished in Java with the help of abstract classes and interfaces.

What is an Abstract Class in Java?

A class that is declared using the keyword abstract is referred to as an abstract class.

Such classes may have both abstract methods (methods without any implementation) and concrete methods(methods with implementation).

Note that, a class that is declared as abstract cannot be instantiated.

One basic rule to be followed with abstract classes is that if any abstract class is extended then that class must have an abstract method, or it should provide the implementation of the method. Otherwise, make the extended class also abstract.

Why is there a need of Abstract Classes in Java?

Let’s take a simple and real example:

Suppose we have a class named SmartPhone that consists of a method androidVersion() and the child classes of this parent class are Xiomi, Moto, Oppo, Nokia, etc.

As we know, every smartphone differs in its version of Android, thus making it useless to define the androidVersion() method in the parent class.  The reason behind this is every smartphone will have to override the method and employ its own details of version like Xiomi can have Android One, Moto can have Android Nougat, etc.

So when the implementation of the method androidVersion() is different for each inherited classes, making the method abstract is the best option.

Now, since the method is the abstract method, declaring the class as abstract is also needed.

Program: How to Achieve Abstraction in Java?

abstract class SmartPhone
{
    abstract  void androidVersio();
    void play()
    {
        System.out.println(“Play music and games”);
    }
}

class Nokia extends Smartphone
{
    void androidVersion()
    {
        System.out.println(“Android 8.1 : Oreo”);
    }
}

class Test
{
    public static void main(String args[])
    {
        SmartPhone s = new Nokia();
        s.androidVersion();
        s.play();
    }
}

Output:

Android 8.1: Oreo
Play music and games

To sum it up, the concept of abstraction deals with the hiding of implementation details and giving the user the access to basic functional details. You can achieve abstraction in Java using abstract classes and interfaces.



Leave a Reply

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