Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
How to achieve Abstraction in Java?
3.
Abstract Class In Java
4.
Abstract Methods In Java
5.
Why can’t we create an object of an Abstract class? 
6.
Types Of Abstraction In Java
7.
Abstraction Using Interface In Java
8.
Abstraction v/s Encapsulation In Java
9.
Advantages Of Abstraction In Java
10.
Frequently Asked Questions
10.1.
Why do I need to use abstract classes in Java?
10.2.
What are the types of abstraction in java?
10.3.
Can I create an object of an abstract class?
10.4.
Can I define a non-abstract method inside an abstract class in java?
10.5.
Can I have constructors inside the abstract class?
11.
Conclusion
Last Updated: Jun 4, 2024

Abstraction In Java

Author Deeksha Sharma
2 upvotes

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 remote that have 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.’

See, Abstract Class and MethodsDuck Number in Java

How to achieve Abstraction in Java?

Abstract class and Interfaces in Java help 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 non-abstract methods, can be implemented inside an abstract class.
  • You can have all types of constructors inside an abstract class like default constructor, or 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
};
You can also try this code with Online Java Compiler
Run Code

Also see,  Swap Function in Java

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;
You can also try this code with Online Java Compiler
Run Code

 

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 called 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();
    }
}
You can also try this code with Online Java Compiler
Run Code

 

You can also read about the Multiple Inheritance in Java and Hashcode Method in Java

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 also try this code with Online Java Compiler
Run Code

 

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
}
You can also try this code with Online Java Compiler
Run Code

 

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.
You can also try this code with Online Java Compiler
Run Code

 

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. 

Must Read Type Conversion in Java

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;
    }
}

You can also try this code with Online Java Compiler
Run Code

 

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

Try: Java Online Compiler

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.

 

Must Read Conditional Statements in Java

Frequently Asked Questions

Why do I need to use abstract classes in Java?

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.

What are the types of abstraction in java?

There are two types of abstraction in java:
Control Abstraction
Data Abstraction

Can I create an object of an abstract class?

No, You can’t create an object of an abstract class because abstract classes can contain abstract methods also.
 

Can I define a non-abstract method inside an abstract class in java?

Yes, you can. You can define a non-abstract method as well as an abstract method inside an abstract class in java.
 

Can I have constructors inside the abstract class?

Yes, you can define all types of constructors like default constructors and parameterized constructors inside the abstract class in java.

Conclusion

So, here we come to 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. 


Recommended Reading:

Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, Uber, Microsoft, etc. on Coding Ninjas Studio.

Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Cheers!

Live masterclass