Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
232 views

Abstraction in Java - GeeksforGeeks

Uploaded by

ashoumik112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
232 views

Abstraction in Java - GeeksforGeeks

Uploaded by

ashoumik112
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

TutorialsDSAData ScienceWeb TechCourses

Abstraction in Java
Last Updated : 15 Dec, 2023
Abstraction in Java is the process in which we only show essential
details/functionality to the user. The non-essential implementation details are
not displayed to the user.

In this article, we will learn about abstraction and what abstract means.

Simple Example to understand Abstraction:


Television remote control is an excellent example of abstraction. It
simplifies the interaction with a TV by hiding the complexity behind
simple buttons and symbols, making it easy without needing to
understand the technical details of how the TV functions.

What is Abstraction in Java?


In Java, abstraction is achieved by interfaces and abstract classes. We can
achieve 100% abstraction using interfaces.

AD

ChatGPT Browser Plugin as your AI OPEN


assistant on any page

Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details. The

https://www.geeksforgeeks.org/abstraction-in-java-2/ 1/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

properties and behaviours of an object differentiate it from other objects of


similar type and also help in classifying/grouping the objects.
Abstraction Real-Life Example:

Consider a real-life example of a man driving a car. The man only knows
that pressing the accelerators will increase the speed of a car or applying
Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Java Exception H
brakes will stop the car, but he does not know how on pressing the
accelerator the speed is actually increasing, he does not know about the
inner mechanism of the car or the implementation of the accelerator,
brakes, etc in the car. This is what abstraction is.

Java Abstract classes and Java Abstract methods


1. An abstract class is a class that is declared with an abstract keyword.
2. An abstract method is a method that is declared without implementation.
3. An abstract class may or may not have all abstract methods. Some of them
can be concrete methods
4. A method-defined abstract must always be redefined in the subclass, thus
making overriding compulsory or making the subclass itself abstract.
5. Any class that contains one or more abstract methods must also be declared
with an abstract keyword.
6. There can be no object of an abstract class. That is, an abstract class can not
be directly instantiated with the new operator.
7. An abstract class can have parameterized constructors and the default
constructor is always present in an abstract class.

Algorithm to implement abstraction in Java

1. Determine the classes or interfaces that will be part of the abstraction.


2. Create an abstract class or interface that defines the common behaviours
and properties of these classes.
3. Define abstract methods within the abstract class or interface that do not
have any implementation details.
4. Implement concrete classes that extend the abstract class or implement the
interface.
https://www.geeksforgeeks.org/abstraction-in-java-2/ 2/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

5. Override the abstract methods in the concrete classes to provide their


specific implementations.
6. Use the concrete classes to implement the program logic.

When to use abstract classes and abstract methods?

There are situations in which we will want to define a superclass that declares
the structure of a given abstraction without providing a complete
implementation of every method. Sometimes we will want to create a
superclass that only defines a generalization form that will be shared by all of
its subclasses, leaving it to each subclass to fill in the details.

Consider a classic “shape” example, perhaps used in a computer-aided design


system or game simulation. The base type is “shape” and each shape has a
color, size, and so on. From this, specific types of shapes are derived(inherited)-
circle, square, triangle, and so on — each of which may have additional
characteristics and behaviours. For example, certain shapes can be flipped.
Some behaviours may be different, such as when you want to calculate the
area of a shape. The type hierarchy embodies both the similarities and
differences between the shapes.

Abstract Class in Java

Java Abstraction Example

Example 1:
https://www.geeksforgeeks.org/abstraction-in-java-2/ 3/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

Java

// Java program to illustrate the


// concept of Abstraction
abstract class Shape {
String color;

// these are abstract methods


abstract double area();
public abstract String toString();

// abstract class can have the constructor


public Shape(String color)
{
System.out.println("Shape constructor called");
this.color = color;
}

// this is a concrete method


public String getColor() { return color; }
}
class Circle extends Shape {
double radius;

public Circle(String color, double radius)


{

// calling Shape constructor


super(color);
System.out.println("Circle constructor called");
this.radius = radius;
}

@Override double area()


{
return Math.PI * Math.pow(radius, 2);
}

@Override public String toString()


{
return "Circle color is " + super.getColor()
+ "and area is : " + area();
}
}
class Rectangle extends Shape {

double length;
double width;

https://www.geeksforgeeks.org/abstraction-in-java-2/ 4/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

public Rectangle(String color, double length,


double width)
{
// calling Shape constructor
super(color);
System.out.println("Rectangle constructor called");
this.length = length;
this.width = width;
}

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

@Override public String toString()


{
return "Rectangle color 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());
}
}

Output

Shape constructor called


Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0

Example 2:

Java

// Java Program to implement

https://www.geeksforgeeks.org/abstraction-in-java-2/ 5/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

// Java Abstraction

// Abstract Class declared


abstract class Animal {
private String name;

public Animal(String name) { this.name = name; }

public abstract void makeSound();

public String getName() { return name; }


}

// Abstracted class
class Dog extends Animal {
public Dog(String name) { super(name); }

public void makeSound()


{
System.out.println(getName() + " barks");
}
}

// Abstracted class
class Cat extends Animal {
public Cat(String name) { super(name); }

public void makeSound()


{
System.out.println(getName() + " meows");
}
}

// Driver Class
public class AbstractionExample {
// Main Function
public static void main(String[] args)
{
Animal myDog = new Dog("Buddy");
Animal myCat = new Cat("Fluffy");

myDog.makeSound();
myCat.makeSound();
}
}

Output

https://www.geeksforgeeks.org/abstraction-in-java-2/ 6/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

Buddy barks
Fluffy meows

Explanation of the above Java program:

This code defines an Animal abstract class with an abstract method


makeSound(). The Dog and Cat classes extend Animal and implement
the makeSound() method. The main() method creates instances of Dog
and Cat and calls the makeSound() method on them.

This demonstrates the abstraction concept in Java, where we define a


template for a class (in this case Animal), but leave the implementation of
certain methods to be defined by subclasses (in this case makeSound()).

Interface
Interfaces are another method of implementing abstraction in Java. The key
difference is that, by using interfaces, we can achieve 100% abstraction in Java
classes. In Java or any other language, interfaces include both methods and
variables but lack a method body. Apart from abstraction, interfaces can also
be used to implement interfaces in Java.

Implementation: To implement an interface we use the keyword


“implements” with class.

Java

// Define an interface named Shape


interface Shape {
double calculateArea(); // Abstract method for
// calculating the area
}

// Implement the interface in a class named Circle


class Circle implements Shape {
private double radius;

https://www.geeksforgeeks.org/abstraction-in-java-2/ 7/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

// Constructor for Circle


public Circle(double radius) { this.radius = radius; }

// Implementing the abstract method from the Shape


// interface
public double calculateArea()
{
return Math.PI * radius * radius;
}
}

// Implement the interface in a class named Rectangle


class Rectangle implements Shape {
private double length;
private double width;

// Constructor for Rectangle


public Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}

// Implementing the abstract method from the Shape


// interface
public double calculateArea() { return length * width; }
}

// Main class to test the program


public class Main {
public static void main(String[] args)
{
// Creating instances of Circle and Rectangle
Circle myCircle = new Circle(5.0);
Rectangle myRectangle = new Rectangle(4.0, 6.0);

// Calculating and printing the areas


System.out.println("Area of Circle: "
+ myCircle.calculateArea());
System.out.println("Area of Rectangle: "
+ myRectangle.calculateArea());
}
}

Output

Area of Circle: 78.53981633974483


Area of Rectangle: 24.0
https://www.geeksforgeeks.org/abstraction-in-java-2/ 8/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

Advantages of Abstraction
Here are some advantages of abstraction:

1. It reduces the complexity of viewing things.


2. Avoids code duplication and increases reusability.
3. Helps to increase the security of an application or program as only essential
details are provided to the user.
4. It improves the maintainability of the application.
5. It improves the modularity of the application.
6. The enhancement will become very easy because without affecting end-
users we can able to perform any type of changes in our internal system.
7. Improves code reusability and maintainability.
8. Hides implementation details and exposes only relevant information.
9. Provides a clear and simple interface to the user.
10. Increases security by preventing access to internal class details.
11. Supports modularity, as complex systems can be divided into smaller and
more manageable parts.
12. Abstraction provides a way to hide the complexity of implementation details
from the user, making it easier to understand and use.
13. Abstraction allows for flexibility in the implementation of a program, as
changes to the underlying implementation details can be made without
affecting the user-facing interface.
14. Abstraction enables modularity and separation of concerns, making code
more maintainable and easier to debug.

Disadvantages of Abstraction in Java


Here are the main disadvantages of abstraction in Java:

1. Abstraction can make it more difficult to understand how the system works.
2. It can lead to increased complexity, especially if not used properly.
3. This may limit the flexibility of the implementation.
4. Abstraction can add unnecessary complexity to code if not used
appropriately, leading to increased development time and effort.
5. Abstraction can make it harder to debug and understand code, particularly
for those unfamiliar with the abstraction layers and implementation details.
https://www.geeksforgeeks.org/abstraction-in-java-2/ 9/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

6. Overuse of abstraction can result in decreased performance due to the


additional layers of code and indirection.

Also Read:

Interfaces in Java
Abstract classes in Java
Difference between abstract class and interface
abstract keyword in Java

Abstraction in Java – FAQs

Q1. Why do we use abstract?

One key reason we use abstract concepts is to simplify complexity.


Imagine trying to explain the entire universe with every single atom and
star! Abstracts let us zoom out, grab the main ideas like gravity and
energy, and make sense of it all without getting lost in the details.

Here are some other reasons why we use abstract in Java:

1. Abstraction: Abstract classes are used to define a generic template for


other classes to follow. They define a set of rules and guidelines that
their subclasses must follow. By providing an abstract class, we can
ensure that the classes that extend it have a consistent structure and
behavior. This makes the code more organized and easier to maintain.

2. Polymorphism: Abstract classes and methods enable polymorphism in


Java. Polymorphism is the ability of an object to take on many forms. This
means that a variable of an abstract type can hold objects of any concrete
subclass of that abstract class. This makes the code more flexible and
adaptable to different situations.

3. Frameworks and APIs: Java has numerous frameworks and APIs that
use abstract classes. By using abstract classes developers can save time

https://www.geeksforgeeks.org/abstraction-in-java-2/ 10/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

and effort by building on existing code and focusing on the aspects


specific to their applications.

Q2. What is the Difference between Encapsulation and Data Abstraction?

Here are some key difference b/w encapsulation and abstration:

Encapsulation Abstraction

Encapsulation is data Abstraction is detailed


hiding(information hiding) hiding(implementation hiding).

Data Abstraction deal with exposing


Encapsulation groups together data
the interface to the user and hiding
and methods that act upon the data
the details of implementation

Encapsulated classes are Java Implementation of abstraction is


classes that follow data hiding and done using abstract classes and
abstraction interface

Encapsulation is a procedure that


takes place at the implementation abstraction is a design-level process
level

Q3. What is a real-life example of data abstraction?

Television remote control is an excellent real-life example of abstraction.


It simplifies the interaction with a TV by hiding the complexity behind
simple buttons and symbols, making it easy without needing to
understand the technical details of how the TV functions.

https://www.geeksforgeeks.org/abstraction-in-java-2/ 11/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

Q4. What is the Difference between Abstract Classes and Interfaces in


Java?

Here are some key difference b/w Abstract Classes and Interfaces in Java:

Abstract Class Interfaces

Abstract classes support abstract Interface supports have abstract


and Non-abstract methods methods only.

Doesn’t support Multiple Inheritance Supports Multiple Inheritance

Abstract classes can be extended by The interface can be extended by


Java classes and multiple interfaces Java interface only.

Abstract class members in Java can


Interfaces are public by default.
be private, protected, etc.

Example: Example:

public abstract class Vechicle{ public interface Animal{


public abstract void drive() void speak();
} }

Feeling lost in the vast world of Backend Development? It's time for a change!
Join our Java Backend Development - Live Course and embark on an exciting
journey to master backend development efficiently and on schedule.
What We Offer:

Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks

https://www.geeksforgeeks.org/abstraction-in-java-2/ 12/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

312 Suggest improvement

Previous Next

Inheritance in Java Encapsulation in Java

Share your thoughts in the comments Add Your Comment

Similar Reads
Abstraction by Parameterization and Difference Between Data Hiding and
Specification in Java Abstraction in Java

Control Abstraction in Java with Difference between Abstraction and


Examples Encapsulation in Java with Examples

Understanding OOPs and Abstraction Understanding Encapsulation,


using Real World Scenario Inheritance, Polymorphism, Abstraction
in OOPs

Difference Between java.sql.Time,


Data Abstraction and Data Independence java.sql.Timestamp and java.sql.Date in
Java

How to Convert java.sql.Date to Different Ways to Convert java.util.Date


java.util.Date in Java? to java.time.LocalDate in Java

G gaurav mi…

Article Tags : Java-Abstract Class and Interface , Java-Object Oriented , Java , Misc
Practice Tags : Java, Misc

https://www.geeksforgeeks.org/abstraction-in-java-2/ 13/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

A-143, 9th Floor, Sovereign Corporate


Tower, Sector-136, Noida, Uttar Pradesh -
201305

Company Explore
About Us Hack-A-Thons
Legal GfG Weekly Contest
Careers DSA in JAVA/C++
In Media Master System Design
Contact Us Master CP
Advertise with us GeeksforGeeks Videos
GFG Corporate Solution Geeks Community
Placement Training Program

Languages DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL Top 100 DSA Interview Problems
R Language DSA Roadmap by Sandeep Jain
Android Tutorial All Cheat Sheets
Tutorials Archive

Data Science & ML HTML & CSS


Data Science With Python HTML
Data Science For Beginner CSS

https://www.geeksforgeeks.org/abstraction-in-java-2/ 14/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

Machine Learning Tutorial Web Templates


ML Maths CSS Frameworks
Data Visualisation Tutorial Bootstrap
Pandas Tutorial Tailwind CSS
NumPy Tutorial SASS
NLP Tutorial LESS
Deep Learning Tutorial Web Design
Django Tutorial

Python Tutorial Computer Science


Python Programming Examples Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps Competitive Programming


Git Top DS or Algo for CP
AWS Top 50 Tree
Docker Top 50 Graph
Kubernetes Top 50 Array
Azure Top 50 String
GCP Top 50 DP
DevOps Roadmap Top 15 Websites for CP

https://www.geeksforgeeks.org/abstraction-in-java-2/ 15/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

System Design JavaScript


High Level Design JavaScript Examples
Low Level Design TypeScript
UML Diagrams ReactJS
Interview Guide NextJS
Design Patterns AngularJS
OOAD NodeJS
System Design Bootcamp Lodash
Interview Questions Web Browser

Preparation Corner School Subjects


Company-Wise Recruitment Process Mathematics
Resume Templates Physics
Aptitude Preparation Chemistry
Puzzles Biology
Company-Wise Preparation Social Science
English Grammar
World GK

Management & Finance Free Online Tools


Management Typing Test
HR Management Image Editor
Finance Code Formatters
Income Tax Code Converters
Organisational Behaviour Currency Converter
Marketing Random Number Generator
Random Password Generator

More Tutorials GeeksforGeeks Videos


Software Development DSA
Software Testing Python
Product Management Java
SAP C++
SEO - Search Engine Optimization Data Science

https://www.geeksforgeeks.org/abstraction-in-java-2/ 16/17
4/25/24, 6:25 PM Abstraction in Java - GeeksforGeeks

Linux CS Subjects
Excel

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

https://www.geeksforgeeks.org/abstraction-in-java-2/ 17/17

You might also like