Abstraction
Abstraction
Summarize
Is this helpful?YesNo
2 trials left
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.
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
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.
double length;
double width;
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 Abstraction
// Abstracted class
// Abstracted class
}
// Driver Class
// Main Function
myDog.makeSound();
myCat.makeSound();
Output
Buddy barks
Fluffy 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 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
}
Output
Advantages of Abstraction
information.
system works.
properly.
implementation details.
Also Read:
● Interfaces in Java
3. Frameworks and APIs: Java has numerous frameworks and APIs that
use abstract classes. By using abstract classes developers can save time
and effort by building on existing code and focusing on the aspects Here
are some key difference b/w encapsulation and abstration:
Encapsulation Abstraction
Encapsulation is data Abstraction is detailed
hiding(information hiding) hiding(implementation hiding).
Encapsulation is a procedure
abstraction is a design-level
that takes place at the
process
implementation level
—----------------------------------------
concrete subclasses.
variables.
interface.
Normal class) that extends an abstract class must override all the
1. final
2. abstract native
3. abstract synchronized
4. abstract static
5. abstract private
6. abstract strict
//body of class
Example 1:
// Parent Class
abstract class gfg {
abstract void printInfo();
}
// Child Class
class employee extends gfg {
void printInfo()
{
String name = "aakanksha";
int age = 21;
float salary = 55552.2F;
System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}
// Driver Class
class base {
// main function
public static void main(String args[])
{
// object created
gfg s = new employee();
s.printInfo();
}
}
aakanksha
21
55552.2
Example 2:
// concrete class B
class B extends A {
// class B must override m1() method
// otherwise, compile-time exception will be thrown
void m1()
{
System.out.println("B's implementation of m1.");
}
}
// Driver class
public class AbstractDemo {
// main function
public static void main(String args[])
{
B b = new B();
b.m1();
b.m2();
}
}
Example 3:
application.
in your code, as you can add new subclasses without changing the
all subclasses, which can prevent errors and improve code quality.
class, you can use late binding to determine which subclass to use
—-----------------------------------------------------------------------
abstract is a Java modifier applicable for classes and methods in Java but
not for Variables. In this article, we will learn the use of abstract classes
in Java.
Java abstract class is a class that can not be initiated by itself, it needs
int color;
// An abstract function
final”
that Child class as abstract so that the next level Child class
// Abstract class
abstract class Sunstar {
abstract void printInfo();
}
System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}
// Base class
class Base {
public static void main(String args[])
{
Sunstar s = new Employee();
s.printInfo();
}
}
avinash
21
222.2
2. Abstract Class having constructor, data member, and methods
● abstract method
● constructor
● main() method.
void Learn(){
System.out.println("Preparing Right Now!");
}
}
class GFG {
public static void main(String[] args) {
Subject x=new IT();
x.syllabus();
x.Learn();
}
}
Learning Subject
C , Java , C++
Preparing Right Now!
Observation 1
// Class 1
// Abstract class
abstract class Base {
abstract void fun();
}
// Class 2
class Derived extends Base {
void fun()
{
System.out.println("Derived fun() called");
}
}
// Class 3
// Main class
class Main {
// Class 1
// Abstract class
abstract class Base {
// Constructor of class 1
Base()
{
// Print statement
System.out.println("Base Constructor Called");
}
// Class 2
class Derived extends Base {
// Constructor of class2
Derived()
{
System.out.println("Derived Constructor Called");
}
// Method of class2
void fun()
{
System.out.println("Derived fun() called");
}
}
// Class 3
// Main class
class GFG {
Observation 3
In Java, we can have an abstract class without any abstract method. This
allows us to create classes that cannot be instantiated but can only be
inherited. It is as shown below as follows with help of a clean java program.
Example:
// Class 1
// An abstract class without any abstract method
abstract class Base {
// Class 2
class Derived extends Base {
// This class only inherits the Base class methods and
// properties
}
// Class 3
class Main {
Observation 4
Abstract classes can also have final methods (methods that cannot be
overridden)
Example:
// Class 1
// Abstract class
abstract class Base {
// Class 2
class Derived extends Base {
// Class 3
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{
{
// Creating object of abstract class
b.fun();
}
}
}
Observation 5
For any abstract java class we are not allowed to create an object i.e., for an
abstract class instantiation is not possible.
// Main class
// An abstract class
abstract class GFG {
Output:
Observation 6
// Class 1
// Abstract class
abstract class Helper {
// Abstract method
static void demofun()
{
// Print statement
System.out.println("Geeks for Geeks");
}
}
// Class 2
// Main class extending Helper class
public class GFG extends Helper {
Observation 7
We can use the abstract keyword for declaring top-level classes (Outer
class) as well as inner classes as abstract
import java.io.*;
abstract class B {
// declaring inner class as abstract with abstract
// method
abstract class C {
abstract void myAbstractMethod();
}
}
class D extends B {
class E extends C {
// implementing the abstract method
void myAbstractMethod()
{
System.out.println(
"Inside abstract method implementation");
}
}
}
Observation 8
import java.io.*;
Hello
Observation 9
class GFG {
public static void main(String[] args)
{
// if we remove the abstract keyword from FirstChild
// Class and uncommented below obj creation for
// FirstChild then it will throw
// compile time error as did't override all the
// abstract methods
// FirstChild f=new FirstChild();
// f.m1();
Inside m1
Inside m2
Inside m3
In C++, if a class has at least one pure virtual function, then the class
becomes abstract. Unlike C++, in Java, a separate keyword abstract is used to
make a class abstract.
Conclusion
Points to remember from this article are mentioned below:
● An abstract class is a class that can not be initiated by itself, it needs
An abstract class in Java is a class that can not be initiated on its own but can
be used as a subclass by another class.
2. What is the abstract class purpose?
The main purpose of the abstract class is to create a base class from which
many other classes can be derived.
—--------------------------------------------------------------------
Cannot be instantiated;
Specifies a set of
contains both abstract
methods a class must
(without
Definition implement; methods
implementation) and
are abstract by
concrete methods (with
default.
implementation)
A class can
class can inherit from
Inheritance implement multiple
only one abstract class.
interfaces.
Methods and properties
Methods and
can have any access
Access Modifiers properties are
modifier (public,
implicitly public.
protected, private).
2. Method Implementation:
3. Variables:
Abstract classes can have member variables, including final, non-final, static,
and non-static variables.
4. Constructors:
Shape(String name) {
this.objectName = name;
}
@Override
public void draw() {
System.out.println("Rectangle has been drawn ");
}
@Override
public double area() {
return (double)(length * width);
}
}
@Override
public double area() {
return (double)(pi * radius * radius);
}
}
System.out.println();
Example 2:
// Abstract class Sunstar
abstract class Sunstar {
// Abstract method printInfo
abstract void printInfo();
}
Avinash
21
222.2
Interface in Java
1. Definition:
3. Variables:
interface Movable {
void moveTo(int x, int y);
}
Circle(int radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle has been drawn ");
}
@Override
public void moveTo(int x, int y) {
System.out.println("Circle has been moved to x = " + x + " and y = " +
y);
}
}
Cannot have
Constructors Can have constructors
constructors
called directly.
base class for other classes, meaning they can be inherited by other
classes. This allows for code reuse and the creation of a common
extensibility.
● Enables separation of concerns: By defining method signatures
interface.
enhancing maintainability.
Overall, interfaces in Java are powerful tools for defining contracts and
promoting flexibility, interoperability, and maintainability in software design.
● In the Java application, there are some related classes that need to
share some lines of code then you can put these lines of code within
the abstract class and this abstract class should be extended by all
class so that via a method you can access and modify the state of
interface.
inheritances.
Summary
Abstract classes in Java serve as blueprints that cannot be instantiated
directly and can include both abstract and concrete methods. They allow for
partial implementation and can contain various types of member variables
with any access modifier. A class can inherit only one abstract class.
Interfaces, on the other hand, are contracts that specify a set of abstract
methods that a class must implement, though they can include default and
static methods from Java 8 onwards. Interfaces enable multiple inheritance of
type, support polymorphism, and enforce a common protocol for different
software components. Unlike abstract classes, all interface methods are
implicitly public, and variables are public, static, and final.
—---------------------------------------------------------------------------------------------------
Control Abstraction in Java with Examples
Last Updated : 11 Jun, 2
Java
abstract class gfg {
abstract void printInfo();
}
System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
class base {
public static void main(String args[]) {
gfg s = new employee();
s.printInfo();
}
}
Output
avinash
21
22332.2
Data abstraction, in short means creating complex data types but giving out
only the essentials operations.
● Control Abstraction follows the basic rule of DRY code which means
Don’t Repeat Yourself and using functions in a program is the best
example of control abstraction.
● Control Abstraction can be used to build new functionalities and
combines control statements into a single unit.
● It is a fundamental feature of all higher-level languages and not just
java.
● Higher-order functions, closures, and lambdas are few preconditions
for control abstraction.
● Highlights more on how a particular functionality can be achieved
rather than describing each detail.
● Forms the main unit of structured programming.
Example:
Java
// Abstract class
abstract class Vehicle {
// Abstract method (does not have a body)
public abstract void VehicleSound();
// Regular method
public void honk() { System.out.println("honk honk"); }
}
class Main {
public static void main(String[] args)
{
// Create a Car object
Car myCar = new Car();
myCar.VehicleSound();
myCar.honk();
}
}
Output
kon kon
honk honk
1. Control Abstraction
Definition:
The goal is to hide the details of how tasks are controlled or performed,
abstraction. The internal logic (the control flow) is hidden from the user. The user
only needs to know how to call the method and what result to expect, without
Example in Java:
java
Copy code
// This is a method that abstracts away the control flow for addition
int result = calc.add(5, 3); // User doesn't need to know how the addition is
done internally
System.out.println(result); // Output: 8
addition happens are abstracted away. The user simply calls add(5, 3)
2. Data Abstraction
Definition:
● Data abstraction refers to the process of hiding the details of how data is
stored and maintained, and providing a simple interface to interact with the
data. It focuses on what data is being used rather than how it is stored or
manipulated.
abstraction. They hide the internal details of how data (attributes) is maintained
and manipulated, exposing only necessary methods to access or modify the data.
Example in Java:
java
Copy code
class BankAccount {
this.balance = initialBalance;
if (amount > 0) {
balance += amount;
return balance;
}
public class Main {
balance
managed internally
class.
● The user interacts with the balance using public methods like deposit() and
getBalance(). They don't need to know how the balance is stored or updated
internally; they just use these methods to interact with the data.
controlled represented
Summary
● Control abstraction simplifies the way operations and control flows are
represented.
manipulated.
—---------------------------------------------------------------------------------------------------
Abstraction Is hiding the internal implementation and just highlight the set of
services. It is achieved by using the abstract class and interfaces and further
implementing the same. Only necessarily characteristics of an object that
differentiates it from all other objects. Only the important details are
emphasized and the rest all are suppressed from the user or reader.
By using ATM GUI screen bank people are highlighting the set of services
what the bank is offering without highlighting internal implementation.
1. Procedural Abstraction
2. Data Abstraction
3. Control Abstraction
2. Data Abstraction: From the word itself, abstraction is achieved from a set
of data that is describing an object.
3. Control Abstraction: Abstraction is achieved in writing the program in
such a way where object details are enclosed.
Advantages of Abstraction:
ob.No_Of_legs();
Now, jumping onto the second concept though both the concepts are used to
achieve encapsulation somehow there is a sleek difference as shown below:
Data Hiding is hiding internal data from outside users. The internal data
should not go directly that is outside person/classes is not able to access
internal data directly. It is achieved by using an access specifier- a private
modifier.
Note: The recommended modifier for data members is private. The main
advantage of data hiding is security
class Account {
……..
…….
}
Here account balance of each say employee is private to each other being
working in the same organization. No body knows account balance of
anybody. In java it is achieved by using a keyword ‘private’ keyword and the
process is called data hiding.
Getter is used to accessing the private data and setter is used to modify the
private data only after authentication. In simple terms, it is hiding internal
data from outside users. It is used as security such that no internal data will
be accessed without authentication. An unauthorized end user will not get
access to internal data. Programmatically we can implement data hiding by
declaring data elements as private. Now to access this data or for
modification, we have a special method known as getter setter respectively.
Now to access this data or for modification, we have a special method known
as getter setter respectively. Getter is used to accessing the private data and
setter is used to modify the private data only after authentication.
// Unauthorised user
return -1;
}
// Setter function
public void set_balance(long balance, long Id)
{
// Comparing bank_id of user and the given Id
// then only it will get access
if (this.bank_id == Id) {
// Update balance in current ID
CurBalance = CurBalance + balance;
}
}
}
// _emp.get_balance(123456)
_emp.set_balance(10000, 12345);
// This will no get access as bank_id is given wrong
// so
// unauthorised user is not getting access that is
// data hiding
// Display commands
System.out.println("User Name"
+ " " + _emp.name);
System.out.println("Bank_ID"
+ " " + _emp.bank_id);
System.out.println("Current Balance"
+ " " + emp_balance);
}
}