Abstraction In Java

Introduction

The term abstraction implies ‘hiding.’ Abstraction in Java deals with hiding complex and unnecessary details from a user. Let us understand this with an example. You switch between different channels on television using your TV remote, but have you ever wondered what actually happens inside the television remote whenever you press a button on it!! That’s where abstraction plays a significant role. See all the complex details of the working of remote has been made hidden from the user. In reality, many things happen inside the television remote with the press of a button. Still, you can use the remote easily without worrying about complex things happening inside it due to the beauty of abstraction.

 

Abstraction in java is a method in which the user can only see the necessary details of a function or object. It hides all the irrelevant data from a user. Abstraction in Java is one of the essential concepts of object-oriented programming. Abstraction is mainly used when we are concerned with ‘what an application does’ instead of ‘how this application does.’

How to achieve Abstraction in Java?

Abstract class and Interfaces in Java helps in achieving abstraction in java. Now, if you want to achieve 100% abstraction, you should go with interfaces; otherwise, partial abstraction can be achieved using abstract classes.

Abstract Class In Java

  • Abstract classes in Java are declared using the abstract keyword.
  • Abstract methods, as well as the non-abstract methods, can be implemented inside an abstract class.
  • You can have all types of constructors inside an abstract class like default constructor, parameterized constructor.
  • You cannot create objects of an abstract class. You can only use objects of its subclass.

 

Syntax Of Declaring an abstract class

abstract class CodingNinja{
      //class body
};

 

Abstract Methods In Java

Methods without a body are known as abstract methods in Java. Method statements are not there in abstract methods. You can declare abstract methods using abstract keywords. Always remember to put a semicolon at the end of an abstract method. One crucial thing about abstract methods in java is that the child class must write the implementation of these abstract methods whenever they inherit the abstract class. Let’s understand it better with the example below.

//Example of an abstract method
abstract void codingNinja();
//As you can see this method has no implementation statements inside it, //Hence it’s an abstract method;

 

Now you must be thinking about why you can’t create an object of an abstract class.

So here is the answer to your confusion:- 

Why can’t we create an object of an Abstract class? 

Suppose Java permits you to make objects of abstract class in java. Now think about what’s going to happen. You will create an object of the abstract class and will try to call abstract methods present in this class with the help of the object you have created.

Now here comes the problem. Abstract methods have no implementation then how will it be worthy of calling such methods? Not at all, Actually abstract class is just like a template, or you can say a blueprint which will be helpful for its child classes in their implementation.

 

So you‘ve read most of the essential concepts of abstraction in java. So now is the time to create our own abstract class. So let’s begin:-

 

//Abstract class having an abstract and non-abstract methods  
abstract class Employee {
    //constructor of the vehicle class
    Employee() {
        System.out.println("Employee is created");

    }

    //abstract method
    abstract void printSalary();

    //non-abstract method
    void designationUpdate() {
        System.out.println("Designation will be updated soon");

    }
}

//child class inheriting an abstract class 
class HR extends Employee {

    void printSalary() {
        System.out.println("printing the salary....");
    }
}

//class calling the abstract and non-abstract methods
class abstractionTest {
    public static void main(String args[]) {
        Employee obj = new HR();
        obj.printSalary();
        obj.designationUpdate();
    }
}

 

Types Of Abstraction In Java

There are two types of abstraction in Java : 

  • Data Abstraction
  • Control Abstraction

 

Data Abstraction:- This is the most common type of abstraction. In this, we create complex data types like hashMap and with the help of abstraction, we hide all the implementation details and only expose the operations necessary for a user to interact with the data type. For example: In a television remote only required operations are exposed to the user, a user never came to know about the complex functioning happening inside with a press of a button.

 

Control Abstraction:- In this abstraction, we identify the statements which are repeating themselves and expose them as a single unit of work to the user. It is generally used while creating a function for some task.

 

// Abstract class
abstract class Animal {
    // Abstract method
    public abstract void AnimalSound();
    //Non-Abstract method
    public void sound() {
        System.out.println("Quack! Quack!");
    }
}

// Subclass (inherit from Animal)
class Cow extends Animal {
    public void AnimalSound() {
        // The body of VehicleSound() is provided here
        System.out.println("Moo! Moo!");
    }
}

class Main {
    public static void main(String[] args) {
        // Create a Cow object
        Cow myCow = new Cow();
        myCow.AnimalSound();
        myCow.sound();
    }
}

Output: 
Moo! Moo!
Quack! Quack!

 

You can infer from the above example that if you want to write a cleaner and safer code then control abstraction is of huge advantage.

 

As we discussed in the blog earlier that we can achieve abstraction using interfaces also in Java. So let’s discuss this in detail.

 

Abstraction Using Interface In Java

Interface in java is a mechanism with which we can achieve complete abstraction in java. Java interface can only contain abstract methods and variables. But now you must be thinking about what exactly the interface implies? The interface is just like a blueprint of a class that contains static variables and abstract methods. Now let’s see how we can declare an Interface in Java. The interface is always declared with the help of an interface keyword.

 

interface CodingNinja{
      //methods and data members
}

 

Always remember these two points about interfaces:-

  • Interface fields by default are public, static, and final.
  • Interface methods are public and abstract by default.

 

So by now, you have understood that interfaces are really helpful if you want to achieve complete abstraction. So before moving on to the next concept, let see its implementation in code.

 

//Interface declaration using interface keyword
interface DrawShapes {
    //abstract method    
    void draw();
}

class Rectangle implements DrawShapes {
    //implementing the abstract method    
    public void draw() {
        System.out.println("Rectangle will be drawn");

    }
}

class Circle implements DrawShapes {
     //implementing the abstract method   
    public void draw() {
        System.out.println("Circle will be drawn");

    }
}

class Testing {
    public static void main(String args[]) {
//creating an object of DrawShapes class        
DrawShapes shape = new Circle();
       //I have implemented the abstract method draw already
        shape.draw();
    }
}

Output: 
Circle will be drawn.

 

I want to discuss a very crucial point here. Remember I have mentioned that interfaces in java contain abstract methods i.e methods having no implementation. But whenever you want to create objects then it’s mandatory for you to write an implementation of these abstract methods. 

Abstraction v/s Encapsulation In Java

You have seen abstraction with examples here. Let's discuss the below code to get an idea about encapsulation.

 

//A Account class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
class Account {
    //private data members
    private long acc_no;
    private String name, email;
    private float amount;
    //public getter and setter methods
    public long getAcc_no() {
        return acc_no;
    }
    public void setAcc_no(long acc_no) {
        this.acc_no = acc_no;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public float getAmount() {
        return amount;
    }
    public void setAmount(float amount) {
        this.amount = amount;
    }
}

 

 

Most of the students find it difficult to differentiate between abstraction and encapsulation. So let us decode the difference between them in points:

 

AbstractionEncapsulation
Abstraction is used to solve the problem at the design level.Encapsulation is used to solve the problem at the implementation level
The purpose of abstraction is to hide unwanted data.The purpose of Encapsulation is to hide the code and data into a single unit so that the outside world can’t access it.
Abstraction is the outer layout that is used in terms of design.Encapsulation is the Inner layout used in terms of implementation.

 

I hope by now you have got the difference between abstraction in Java and Encapsulation in Java. So let’s move towards the advantages of using abstract classes in Java.

Advantages Of Abstraction In Java

Abstraction in Java solves many issues. Let’s discuss them one by one:

 

  • Abstraction helps a lot in reducing the complexity of viewing things.

 

  • Abstraction in Java is necessary for controlling code duplication.

 

  • Abstraction in Java only exposes the details which are necessary for a user. Hence it increases the security and confidentiality of a program.

Frequently Asked Questions

  1. Why do I need to use abstract classes in Java?
    Ans 1. You need abstract classes in Java so that you can hide irrelevant details of a program from the user and can expose only the relevant functions of a program to the end-user.
     
  2. What are the types of abstraction in java?
    Ans 2. There are two types of abstraction in java:
                Control Abstraction
                Data Abstraction
     
  3. Can I create an object of an abstract class?
    Ans 3. No, You can’t create an object of an abstract class because abstract classes can contain abstract methods also.
     
  4. Can I define a non-abstract method inside an abstract class in java?
    Ans 4. Yes, you can. You can define a non-abstract method as well as an abstract method inside an abstract class in java.
     
  5. Can I have constructors inside the abstract class?
    Ans 5. Yes, you can define all types of constructors like default constructors and parameterized constructors inside the abstract class in java.

Key Takeaways

So, here we come at the end of abstraction in Java. Always remember the concept of abstraction in Java is beneficial in hiding irrelevant details from a user. Here we learned about abstract methods and non-abstract methods inside an abstract class in Java. One should always pay attention to the fact that we can create an abstract class in Java. We’ve also discussed the difference between Encapsulation and abstraction in Java which is asked in most of the interviews. I hope now you must be clear with all the concepts regarding abstraction in Java. 


Thank you for reading this article, and do share it on social media so that it can add value to your friend’s knowledge also. You can learn more about java here. Happy Coding!

Was this article helpful ?
1 upvote

Comments

No comments yet

Be the first to share what you think