Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconHow to Implement Data Abstraction in Java?

How to Implement Data Abstraction in Java?

Last updated:
17th May, 2022
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
How to Implement Data Abstraction in Java?

Abstraction, polymorphism, encapsulation, and inheritance are the four basic elements of object-oriented programming. One of them, Data Abstraction, will be discussed in detail in the following article. We will also learn how to perform data abstraction in Java.

What is Data Abstraction?

Data abstraction is the characteristic feature where just the most important details are shown to the user. The user is kept unaware of the trivial or non-essential details. For example, an automobile is considered as a whole rather than its distinct parts. The practice of identifying only the needed attributes of an item while discarding the extraneous information is known as data abstraction. 

 

In simple terms, data abstraction displays important items to the user while keeping insignificant elements hidden.

Ads of upGrad blog

 

We use the keyword “abstract” to implement abstraction with the help of classes and interfaces. We can have both abstract and concrete methods in abstract classes.

What are Abstract Classes?

In Object-Oriented Programming, an abstract class is a class that declares one or more abstract methods. The sole distinction between abstract and regular Java classes is that abstract classes contain the abstract keyword, whereas regular Java classes do not. For the declaration of an abstract class, we use the abstract keyword before its class name. There can be both abstract and concrete methods in classes. However, abstract methods can’t be present in regular classes. A class with at least one abstract method is referred to as an abstract class.

 

Its syntax is: 

public abstract class Name_of_Class  

{  

public abstract Name_of_Method();  

}  

 

An example of implementing abstract class is: 

 

//abstract class naming

abstract class DemoClass  

{  

//abstract method naming

abstract void disp();  

}  

//proceeding with the abstract class  

public class MainClass extends DemoClass  

{  

//defining the abstract class’s method body

void display()  

{  

System.out.println(“Abstract method called.”);  

}  

public static void main(String[] args)  

{    

MainClass obj = new MainClass ();  

//invoking abstract method  

obj.display();  

}  

}  

 

To list pointwise: 

 

  • A class must be defined as abstract if it has at least one abstract method.
  • A class that has been declared abstract cannot be instantiated.
  • You must inherit an abstract class from another class and supply implementations for its abstract methods to utilise it.
  • You must supply implementations for all abstract methods in an abstract class if you inherit it.

What are Abstract Methods?

An abstract method has only the method declaration and no implementation. An abstract method can be represented by a method without a body of its own. Abstract methods must be declared exclusively within abstract classes.

 

If you want a class to have a method but the actual implementation of that method to be determined by child classes, designate the method as an abstract in the parent class.

Advantages of Data Abstraction in Object-Oriented Programming

 

  • In Object-Oriented Programming, abstraction reduces the complexity of the programme design and the process of its implementation on software.
  • The foremost advantage of implementing abstraction in Java programming is that users can then easily organise classes based on similarities, such as siblings, and therefore, inheritance of data and migration of data becomes easy and feasible.
  • Inheritance is possible. For example: 

 

/* File name : DemoAbstract.java */

public class DemoAbstract {

 

   public static void main(String [] args) {

      /* the following cannot be written and initiate errors */

      employee e = new employee(“Peter D.”, “Hartford, CT”, 35);

      System.out.println(“\n Use Employee reference and call MailCheck–“);

      e.mailCheck();

   }

}

 

This shows the following error:

 

Employee.java:46: Employee is abstract; cannot be instantiated

 

      employee e = new employee(“Peter D.”, “Hartford, CT”, 35);

                   ^

1 error

 

So we use the abstract class usage as:

 

/* File name : employee.java */

public abstract class employee {

   private String N;

   private String Add;

   private int Num;

 

   public Employee(String N, String Add, int Num) {

      System.out.println(“Constructing an employee”);

      this.name = N;

      this.address = Add;

      this.number = Num;

   }

   

   public double compute_pay() {

     System.out.println(“Inside employee compute_pay”);

     return 0.0;

   }

   

   public void Mailcheck() {

      System.out.println(“Mailing a check to ” + this.name + ” ” + this.address);

   }

 

   public String toString() {

      return N + ” ” + Add + ” ” + N;

   }

 

   public String getName() {

      return N;

   }

 

   public String getAddress() {

      return Add;

   }

   

   public void setAddress(String newAddress) {

      Add = newAddress;

   }

 

   public int getNumber() {

      return Num;

   }

}

When do we use abstract class or abstract methods? 

When we consider the general  example of “shapes”, we may imagine it being used in reference to a computer-aided design system or for a video game simulation. The fundamental type referred to here is a “shape,” with every shape having its own color attributes, size, etc. Specific classes of shapes-circle, square, triangle, etc., are derived (inherited) from this, each of which may have extra unique properties and behaviors. Certain shapes, for example, can be symmetrical, while others are not. Both the similarities and distinct differences between the shapes are embodied in the type hierarchy.

Therefore, shape can be analogous to an abstract class, while the different types of shapes can be denoted as concrete classes. 

 

Here is a real-life scenario to explain abstract classes:

 

// Java program to demonstrate Abstraction

abstract class shape {

String colour;

 

abstract double area();

public abstract String toString();

 

// abstract class can have the constructor

public shape(String colour)

{

System.out.println(“Shape constructor called”);

this.colour = colour;

}

 

// this is a concrete method

public String getColour() { return colour; }

}

class Circle extends shape {

double r;

 

public Circle(String colour, double(r)

{

 

// calling Shape constructor

super(colour);

System.out.println(“Circle constructor called”);

this.r = r;

}

 

@Override double area()

{

return Math.PI * Math.pow(r, 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 colour, double length,

double width)

{

// calling Shape constructor

super(colour);

System.out.println(“Rectangle constructor called”);

this.length = length;

this.width = width;

}

 

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

 

@Override public String toString()

{

return “Rectangle colour 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());

}

}

 

This segment of code is a modified version of the one here.

 

A code snippet of a program where data abstraction in Java is used:

 

 // Abstraction in Java

abstract class ElecBill

{

    //abstract method

    abstract float compBill();

}

 

class Comm extends ElecBill

{

    

    float compBill() {

        return 1.00*100;

    }

}

class Domestic extends ElecBill

{

    float compBill() {

        return 0.50*75;

    }

}

 

Conclusion 

Ads of upGrad blog

Data abstraction is an important aspect of object-oriented programming. For languages like Java, abstraction and other OOP concepts like inheritance, encapsulation, and polymorphism play a crucial role in writing efficient programs.

If you’d like to learn OOPs in in-depth and acquire first-class programming skills, we recommend joining upGrad’s Job-linked PG Certification in Software Engineering which is designed to help students acquire skills in Java, OODAP, DSA, HTML5, CSS3, JavaScript, MERN, AWS, SQL & NoSQL Databases, Spring Boot, etc. The 5-month course covers two specialisations – MERN Stack Specialization and Cloud-Native Specialization and provides access to upGrad 360° career counselling sessions.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1What is polymorphism? How is it different from data abstraction?

Polymorphism is a generalization, similar to data abstraction, but it occurs at runtime. If there is a mechanism to access a collection of distinct object types in which they are indistinguishable from one another, they are polymorphic. So, even if they are not identical, all of the objects within have the same appearance and feel. The goal is to drastically decrease coding. Instead of writing all of the numerous permutations for each individual type, you can write one universal solution.

2What are the differences between Encapsulation and Data Abstraction?

ENCAPSULATION - 1. Encapsulation hides data (information), whereas abstraction hides details (implementation hiding). 2. Object-Oriented Programming's abstraction solves problems at the design level. 3. For security purposes, encapsulation implies hiding the internal information or mechanics of how an object performs something. ABSTRACTION - 1. While encapsulation binds together data and methods that operate on it, data abstraction is concerned with exposing the user interface while obscuring implementation details. 2. It is solved at the implementation level through encapsulation. 3. In Java, data abstraction allows you to concentrate on what the information object must include.

3What are the distinguishing features between interface and abstract class?

Interface - 1. Only abstract methods find themselves to be a part of the interface. 2. Multiple inheritances are supported. 3. It is unable to offer the abstract class's implementation. 4. Only public abstract methods are allowed in an interface. 5. Only one public static final variable can be used in the interface. Abstract class - 1. Abstract, as well as non-abstract methods, can be found in an abstract class. 2. Multiple inheritances are not supported. 3. It is capable of implementing the interface. 4. Protected and abstract public methods are both possible in an abstract class. 5. With any access specifier, an abstract class can have final, static, or static final variables.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 14 Technical Courses to Get a Job in IT Field in India [2024]
90952
In this Article, you will learn about top 14 technical courses to get a job in IT. Software Development Data Science Machine Learning Blockchain Mana
Read More

by upGrad

15 Jul 2024

25 Best Django Project Ideas & Topics For Beginners [2024]
143863
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

11 Jul 2024

Must Read 50 OOPs Interview Questions & Answers For Freshers & Experienced [2024]
124781
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

04 Jul 2024

Understanding Exception Hierarchy in Java Explained
16878
The term ‘Exception’ is short for “exceptional event.” In Java, an Exception is essentially an event that occurs during the ex
Read More

by Pavan Vadapalli

04 Jul 2024

33 Best Computer Science Project Ideas & Topics For Beginners [Latest 2024]
198249
Summary: In this article, you will learn 33 Interesting Computer Science Project Ideas & Topics For Beginners (2024). Best Computer Science Proje
Read More

by Pavan Vadapalli

03 Jul 2024

Loose Coupling vs Tight Coupling in Java: Difference Between Loose Coupling & Tight Coupling
65177
In this article, I aim to provide a profound understanding of coupling in Java, shedding light on its various types through real-world examples, inclu
Read More

by Rohan Vats

02 Jul 2024

Top 58 Coding Interview Questions & Answers 2024 [For Freshers & Experienced]
44555
In coding interviews, a solid understanding of fundamental data structures like arrays, binary trees, hash tables, and linked lists is crucial. Combin
Read More

by Sriram

26 Jun 2024

Top 10 Features & Characteristics of Cloud Computing in 2024
16289
Cloud computing has become very popular these days. Businesses are expanding worldwide as they heavily rely on data. Cloud computing is the only solut
Read More

by Pavan Vadapalli

24 Jun 2024

Top 10 Interesting Engineering Projects Ideas & Topics in 2024
43094
Greetings, fellow engineers! As someone deeply immersed in the world of innovation and problem-solving, I’m excited to share some captivating en
Read More

by Rohit Sharma

13 Jun 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon