0% found this document useful (0 votes)
56 views

.Trashed-1742732428-Abstraction in Java - GeeksforGeeks

The document explains the concept of abstraction in Java, which involves hiding implementation details and exposing only essential functionalities to simplify user interaction. It discusses the use of abstract classes and interfaces to achieve abstraction, providing examples and outlining the advantages and disadvantages of using abstraction in programming. Additionally, it differentiates between abstraction and encapsulation, as well as abstract classes and interfaces.

Uploaded by

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

.Trashed-1742732428-Abstraction in Java - GeeksforGeeks

The document explains the concept of abstraction in Java, which involves hiding implementation details and exposing only essential functionalities to simplify user interaction. It discusses the use of abstract classes and interfaces to achieve abstraction, providing examples and outlining the advantages and disadvantages of using abstraction in programming. Additionally, it differentiates between abstraction and encapsulation, as well as abstract classes and interfaces.

Uploaded by

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

Java Course Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithrea

Abstraction in Java
Last Updated : 10 Jan, 2025

Abstraction in Java is the process of hiding the implementation details


and only showing the essential functionality or features to the user. This
helps simplify the system by focusing on what an object does rather
than how it does it. The unnecessary details or complexities are not
displayed to the user.

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.

Example:

// Demonstrating Abstraction in Java


abstract class Geeks {
abstract void turnOn();
abstract void turnOff();
}

// Concrete class implementing the abstract methods


class TVRemote extends Geeks {
@Override
void turnOn() {
System.out.println("TV is turned ON.");
}

@Override
void turnOff() {
System.out.println("TV is turned OFF.");
}
}

We //
use cookies to ensuretoyoudemonstrate
Main class have the best browsing experience on our website. By using our site, you
abstraction
publicacknowledge that you have read and understood our Cookie Policy & Privacy Policy
class Main {
public static void main(String[] args) {
Got It !
Geeks remote = new TVRemote();
remote.turnOn();
remote.turnOff();
}
}

Output

TV is turned ON.
TV is turned OFF.

Explanation: In the above example, the “Geeks” abstract class hides


implementation details and defines the essential methods turnOn and
turnOff. The TVRemote class provides specific implementations for
these methods. The main class demonstrates how the user interacts
with the abstraction without needing to know the internal details.

In Java, abstraction is achieved by interfaces and abstract classes. We


can achieve 100% abstraction using interfaces. Data Abstraction may
also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The
properties and behaviors 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 accelerator will increase the speed of a
car or applying 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.

Abstract Classes and Abstract Methods

An abstract class is a class that is declared with an abstract keyword.


An
We use abstract
cookies method
to ensure you have is
theabest
method
browsingthat is declared
experience without
on our website. By using our site, you
implementation.
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
An abstract class may or may not have all abstract methods. Some of
them can be concrete methods
A abstract method must always be redefined in the subclass, thus
making overriding compulsory or making the subclass itself abstract.
Any class that contains one or more abstract methods must also be
declared with an abstract keyword.
There can be no object of an abstract class. That is, an abstract class
can not be directly instantiated with the new operator.
An abstract class can have parameterized constructors and the
default constructor is always present in an abstract class.

Algorithm to Implement Abstraction

Determine the classes or interfaces that will be part of the


abstraction.
Create an abstract class or interface that defines the common
behaviors and properties of these classes.
Define abstract methods within the abstract class or interface that do
not have any implementation details.
Implement concrete classes that extend the abstract class or
implement the interface.
Override the abstract methods in the concrete classes to provide
their specific implementations.
Use the concrete classes to contain 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
We use cookiesatoclassic
ensure you“shape” example,
have the best perhapsonused
browsing experience in a computer-aided
our website. By using our site, you
designacknowledge
system or thatgame
you havesimulation.
read and understood our Cookie
The base typePolicy
is &“shape”
Privacy Policy
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 behaviors. For example, certain
shapes can be flipped. Some behaviors 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.

Example 1:

// 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


We use cookiessuper(color);
to ensure you have the best browsing experience on our website. By using our site, you
System.out.println("Circle constructor called");
acknowledge that you have
this.radius read and understood our Cookie Policy & Privacy Policy
= 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;

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
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Rectangle color is Yellowand area is : 8.0
acknowledge that you have read and understood our Cookie Policy & Privacy Policy

Example 2: Let’s see another example to understand abstraction in Java.


// 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 Geeks {

// Main Function
public static void main(String[] args)
{
Animal myDog = new Dog("ABC");
Animal myCat = new Cat("XYZ");

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

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Output
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
ABC barks
XYZ meows

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 inheritance in
Java.

Implementation: To implement an interface we use the keyword


“implements” with class.

Example: Below is the Implementation of Abstraction using Interface.

// 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 r; // radius

// Constructor for Circle


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

// Implementing the abstract method


// from the Shape interface
public double calculateArea()
{
return Math.PI * r * r;
}
}

// Implement the interface in a


// class named Rectangle
class Rectangle implements Shape {
We use cookies
privateto ensure you have
double the best browsing experience on our website. By using our site, you
length;
acknowledge
private that youwidth;
double have read and understood our Cookie Policy & Privacy Policy

// 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 c = new Circle(5.0);
Rectangle rect = new Rectangle(4.0, 6.0);

System.out.println("Area of Circle: "


+ c.calculateArea());
System.out.println("Area of Rectangle: "
+ rect.calculateArea());
}
}

Output

Area of Circle: 78.53981633974483


Area of Rectangle: 24.0

Advantages of Abstraction

Simplifies complex systems by hiding implementation details.


Increases code reusability and maintainability.
Enhances security by exposing only essential features.
Improves modularity and separation of concerns.
Provides a clear and user-friendly interface.

Disadvantages of Abstraction

It can add unnecessary complexity if overused.


We use
Maycookies to ensure
reduce you have theinbest
flexibility browsing experience on our website. By using our site, you
implementation.
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Makes debugging and understanding the system harder for
unfamiliar users.
Overhead from abstraction layers can affect performance.

Abstractions in Java Visit Course

FAQs

Why do we use abstract?

Abstraction simplifies complexity: It is used to simplify the


complexity and make easier for both user and end users. we can
use abstraction to hide details and show nececcary part .

Benefits:

Structure and Consistency: Abstract classes enforce a common


structure and behavior among subclasses.
Polymorphism: Enables treating objects of different subclasses
uniformly.
Reusability: Leverages existing frameworks and APIs, saving
development time.
Better Code Organization: Abstract classes promote better
code organization by establishing a clear hierarchy and
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
relationships between different classes.
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Java has numerous frameworks and APIs that use abstract
classes. By using abstract classes developers can save time and
effort by building on existing

What is the Difference between Encapsulation and Data


Abstraction?

Here are some key difference between encapsulation and


abstraction:

Encapsulation Abstraction

Encapsulation is data Abstraction is detailed


hiding(information hiding) hiding(implementation hiding).

Data Abstraction deals with


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

Encapsulated classes are Java Implementation of abstraction is


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

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

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.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy
What is the Difference between Abstract Classes and Interfaces
in Java?

Here are some key difference between Abstract Classes and


Interfaces in Java:

Abstract Class Interfaces

Abstract classes support Interface in Java can have


abstract and Non-abstract abstract methods, default
methods. methods, and static methods.

Doesn’t support Multiple


Supports Multiple Inheritance.
Inheritance.

Abstract classes can be


The interface can be extended
extended by Java classes and
by Java interface only.
multiple interfaces

Abstract class members in Java


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

Example: Example:

public abstract class Vehicle{ public interface Animal{


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

Kickstart your Java journey with our online course on Java


Programming, covering everything from basics to advanced concepts.
Complete real-world coding challenges and gain hands-on
experience. Join the Three 90 Challenge—finish 90% in 90 days for a
90% refund. Start mastering Java today!
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our Cookie Policy & Privacy Policy

You might also like