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 Blogs

Marquee Tag & Attributes in HTML: Features, Uses, Examples
5032
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5012
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5017
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5010
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions & Answers (Freshers & Experienced)
5057
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

10 Best Software Engineering Colleges (India and Global) 2024
5211
Software Engineering is developing, designing, examining, and preserving software. It is a structured and trained approach through which you can devel
Read More

by venkatesh Rajanala

28 Feb 2024

What is Composition in Java With Examples
66379
Java is a versatile language that supports object-oriented programming and code reusability with building relationships between two classes. There are
Read More

by Arjun Mathur

19 Feb 2024

Software Engineer / Developer Salary in India in 2024 [For Freshers & Experienced]
908085
Summary: In this article, you will learn about Software Engineer Salary in India based on Location, Skills, Experience, country and more. Today softw
Read More

by Rohan Vats

Top 40 Most Common CSS Interview Questions and Answers [For Freshers & Experienced]
15456
Every industry has started the use of websites and applications to catch up with the pace of the rapidly transforming world. CSS is one of the most cr
Read More

by Rohan Vats

19 Feb 2024

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