0% found this document useful (0 votes)
24 views74 pages

Abstraction

Uploaded by

prachibpatel2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views74 pages

Abstraction

Uploaded by

prachibpatel2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Abstraction in Java

Last Updated : 29 Jul, 2024



Summarize

Abstraction in Java involves showing essential details of functionality to users while


hiding non-essential implementation details. This article explains abstraction using a
simple example, such as a television remote control, which hides the complexity of TV
functions behind simple buttons. Key Pointers Achieved through interfaces and
abstract classes in Java. Helps identify required characteristics of objects, ignoring
irrelevant details. Abstract class Declared with 'abstract' keyword contains abstract
and concrete methods. Abstract methods Must be redefined in subclasses, making
overriding compulsory. Abstract classes Cannot be instantiated directly but can have
constructors. Steps to implement abstraction Determine class or interface for
abstraction. Create abstract class or interface with common behavior and properties.
Define abstract methods. Implement concrete classes extending abstract class or
implementing interface. Use concrete classes for program logic. Abstract classes
define a superclass structure without complete implementation for every method.
Example 'Shape' class with subclasses 'Circle' and 'Rectangle' demonstrating
inheritance and method overriding. Another example Abstract 'Animal' class with
'Dog' and 'Cat' subclasses implementing the 'makeSound' method. Benefits Reduces
complexity, avoids code duplication, increases reusability, enhances security, improves
maintainability and modularity. Challenges Can make understanding the system more
difficult and potentially decrease performance due to additional code layers. Key
differences Encapsulation groups data and methods data hiding, while abstraction
hides implementation details. Abstract classes vs. interfaces Abstract classes can
have both types of methods and support multiple inheritances interfaces support only
abstract methods and public default methods.

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.

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.
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 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
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
behaviors 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.
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 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.

Java Abstraction Example


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

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 Program to implement

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

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;

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

Advantages of Abstraction

Here are some advantages of abstraction:


● It reduces the complexity of viewing things.

● Avoids code duplication and increases reusability.


● Helps to increase the security of an application or program as

only essential details are provided to the user.

● It improves the maintainability of the application.

● It improves the modularity of the application.

● The enhancement will become very easy because without

affecting end-users we can able to perform any type of changes

in our internal system.

● Improves code reusability and maintainability.

● Hides implementation details and exposes only relevant

information.

● Provides a clear and simple interface to the user.

● Increases security by preventing access to internal class details.

● Supports modularity, as complex systems can be divided into

smaller and more manageable parts.

● Abstraction provides a way to hide the complexity of

implementation details from the user, making it easier to

understand and use.

● 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.

● 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:


● Abstraction can make it more difficult to understand how the

system works.

● It can lead to increased complexity, especially if not used

properly.

● This may limit the flexibility of the implementation.

● Abstraction can add unnecessary complexity to code if not used

appropriately, leading to increased development time and effort.

● Abstraction can make it harder to debug and understand code,

particularly for those unfamiliar with the abstraction layers and

implementation details.

● 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


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
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).

Data Abstraction deal with


Encapsulation groups together
exposing the interface to the user
data and methods that act upon
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.

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

Interface in Java can have abstract


Abstract classes support abstract and
methods, default methods, and static
Non-abstract methods.
methods.

Doesn’t support Multiple Inheritance. Supports Multiple Inheritance.

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


Java classes and multiple interfaces interface only.

Abstract class members in Java can be


Interfaces are public by default.
private, protected, etc.
Example:
Example:

public abstract class Vechicle{


public interface Animal{
public abstract void drive()
void speak();
}

pecific to their applications.

—----------------------------------------

abstract keyword in java


Last Updated : 02 Apr, 2024



In Java, abstract is a non-access modifier in java applicable for

classes, and methods but not variables. It is used to achieve

abstraction which is one of the pillars of Object Oriented

Programming(OOP). Following are different contexts where abstract

can be used in Java.

Characteristics of Java Abstract Keyword


In Java, the abstract keyword is used to define abstract classes and

methods. Here are some of its key characteristics:

● Abstract classes cannot be instantiated: An abstract class is

a class that cannot be instantiated directly. Instead, it is

meant to be extended by other classes, which can provide

concrete implementations of its abstract methods.

● Abstract methods do not have a body: An abstract method is

a method that does not have an implementation. It is

declared using the abstract keyword and ends with a

semicolon instead of a method body. Subclasses of an

abstract class must provide a concrete implementation of all

abstract methods defined in the parent class.

● Abstract classes can have both abstract and concrete

methods: Abstract classes can contain both abstract and

concrete methods. Concrete methods are implemented in the

abstract class itself and can be used by both the abstract

class and its subclasses.

● Abstract classes can have constructors: Abstract classes can

have constructors, which are used to initialize instance

variables and perform other initialization tasks. However,

because abstract classes cannot be instantiated directly,


their constructors are typically called constructors in

concrete subclasses.

● Abstract classes can contain instance variables: Abstract

classes can contain instance variables, which can be used by

both the abstract class and its subclasses. Subclasses can

access these variables directly, just like any other instance

variables.

● Abstract classes can implement interfaces: Abstract classes

can implement interfaces, which define a set of methods that

must be implemented by any class that implements the

interface. In this case, the abstract class must provide

concrete implementations of all methods defined in the

interface.

Overall, the abstract keyword is a powerful tool for defining abstract

classes and methods in Java. By declaring a class or method as

abstract, developers can provide a structure for subclassing and

ensure that certain methods are implemented in a consistent way

across all subclasses.

Abstract Methods in Java


Sometimes, we require just method declaration in super-classes. This

can be achieved by specifying the abstract type modifier. These

methods are sometimes referred to as subclass responsibility because

they have no implementation specified in the super-class. Thus, a

subclass must override them to provide a method definition. To

declare an abstract method, use this general form:

abstract type method-name(parameter-list);

As you can see, no method body is present. Any concrete class(i.e.

Normal class) that extends an abstract class must override all the

abstract methods of the class.

Important rules for abstract methods

There are certain important rules to be followed with abstract

methods as mentioned below:

● Any class that contains one or more abstract methods must

also be declared abstract

● The following are various illegal combinations of other

modifiers for methods with respect to abstract modifiers:

1. final
2. abstract native

3. abstract synchronized

4. abstract static

5. abstract private

6. abstract strict

Abstract Classes in Java

The class which is having partial implementation(i.e. not all methods

present in the class have method definitions). To declare a class

abstract, use this general form :

abstract class class-name{

//body of class

Due to their partial implementation, we cannot instantiate abstract

classes. Any subclass of an abstract class must either implement all

of the abstract methods in the super-class or be declared abstract

itself. Some of the predefined classes in Java are abstract. They

depend on their sub-classes to provide a complete implementation.

For example, java.lang.Number is an abstract class. For more on

abstract classes, see abstract classes in Java.


Examples of abstract Keyword

Example 1:

// Java Program to implement


// Abstract Keywords

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

// Java program to demonstrate


// use of abstract keyword.

// abstract with class


abstract class A {
// abstract with method
// it has no body
abstract void m1();

// concrete methods are still


// allowed in abstract classes
void m2()
{
System.out.println("This is a concrete method.");
}
}

// 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();
}
}

B's implementation of m1.


This is a concrete method.

Example 3:

// Define an abstract class


abstract class Shape {
// Define an abstract method
public abstract double getArea();
}

// Define a concrete subclass of Shape


class Circle extends Shape {
private double radius;

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


public double getArea()
{
return Math.PI * radius * radius;
}
}

// Define another concrete subclass of Shape


class Rectangle extends Shape {
private double width;
private double height;

public Rectangle(double width, double height)


{
this.width = width;
this.height = height;
}

public double getArea() { return width * height; }


}

// Use the Shape class and its subclasses


public class Main {
public static void main(String[] args)
{
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(10, 20);

System.out.println("Circle area: "


+ circle.getArea());
System.out.println("Rectangle area: "
+ rectangle.getArea());
}
}

Circle area: 78.53981633974483


Rectangle area: 200.0

Note : Although abstract classes cannot be used to instantiate objects, they


can be used to create object references, because Java’s approach to run-time
polymorphism is implemented through the use of super-class references.
Thus, it must be possible to create a reference to an abstract class so that it
can be used to point to a subclass object.

Advantages of Abstract Keywords

Here are some advantages of using the abstract keyword in Java:


● Provides a way to define a common interface: Abstract classes can

define a common interface that can be used by all subclasses. By

defining common methods and properties, abstract classes provide

a way to enforce consistency and maintainability across an

application.

● Enables polymorphism: By defining a superclass as abstract, you

can create a collection of subclasses that can be treated as instances

of the superclass. This allows for greater flexibility and extensibility

in your code, as you can add new subclasses without changing the

code that uses them.

● Encourages code reuse: Abstract classes can define common

methods and properties that can be reused by all subclasses. This


saves time and reduces code duplication, which can make your code

more efficient and easier to maintain.

● Provides a way to enforce implementation: Abstract methods must

be implemented by any concrete subclass of the abstract class. This

ensures that certain functionality is implemented consistently across

all subclasses, which can prevent errors and improve code quality.

● Enables late binding: By defining a common interface in an abstract

class, you can use late binding to determine which subclass to use

at runtime. This allows for greater flexibility and adaptability in your

code, as you can change the behavior of your program without

changing the code itself.

abstract and final class in Java


In Java, you will never see a class or method declared with both final and
abstract keywords. For classes, final is used to prevent inheritance whereas
abstract classes depend upon their child classes for complete
implementation. In cases of methods, final is used to prevent overriding
whereas abstract methods need to be overridden in sub-classes.
To know more about the difference between them refer to Difference
between Final and Abstract in Java article.

—-----------------------------------------------------------------------

Abstract Class in Java


Last Updated : 26 Sep, 2023



In Java, abstract class is declared with the abstract keyword. It may

have both abstract and non-abstract methods(methods with bodies). An

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.

What is Abstract Class in Java?

Java abstract class is a class that can not be initiated by itself, it needs

to be subclassed by another class to use its properties. An abstract class

is declared using the “abstract” keyword in its class definition.

Illustration of Abstract class

abstract class Shape

int color;

// An abstract function

abstract void draw();

In Java, the following some important observations about abstract

classes are as follows:


1. An instance of an abstract class can not be created.

2. Constructors are allowed.

3. We can have an abstract class without any abstract method.

4. There can be a final method in abstract class but any abstract

method in class(abstract class) can not be declared as final or in

simpler terms final method can not be abstract itself as it will

yield an error: “Illegal combination of modifiers: abstract and

final”

5. We can define static methods in an abstract class

6. We can use the abstract keyword for declaring top-level

classes (Outer class) as well as inner classes as abstract

7. If a class contains at least one abstract method then

compulsory should declare a class as abstract

8. If the Child class is unable to provide implementation to all

abstract methods of the Parent class then we should declare

that Child class as abstract so that the next level Child class

should provide implementation to the remaining abstract method

Examples of Java Abstract Class

1. Example of Abstract Class that has Abstract method


Below is the implementation of the above topic:

// Abstract class
abstract class Sunstar {
abstract void printInfo();
}

// Abstraction performed using extends


class Employee extends Sunstar {
void printInfo()
{
String name = "avinash";
int age = 21;
float salary = 222.2F;

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

Elements abstract class can have


● data member

● abstract method

● method body (non-abstract method)

● constructor

● main() method.

Below is the implementation of the above topic:

// Java Program to implement Abstract Class


// having constructor, data member, and methods
import java.io.*;

abstract class Subject {


Subject() {
System.out.println("Learning Subject");
}

abstract void syllabus();

void Learn(){
System.out.println("Preparing Right Now!");
}
}

class IT extends Subject {


void syllabus(){
System.out.println("C , Java , C++");
}
}

class GFG {
public static void main(String[] args) {
Subject x=new IT();

x.syllabus();
x.Learn();
}
}

Learning Subject
C , Java , C++
Preparing Right Now!

Properties of Abstract class


Let us elaborate on these observations and do justify them with help of clean
java programs as follows.

Observation 1

In Java, just like in C++ an instance of an abstract class cannot be created, we


can have references to abstract class type though. It is as shown below via
the clean Java program.
Example

// Java Program to Illustrate


// that an instance of Abstract
// Class can not be created

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

// Main driver method


public static void main(String args[])
{

// Uncommenting the following line will cause


// compiler error as the line tries to create an
// instance of abstract class. Base b = new Base();

// We can have references of Base type.


Base b = new Derived();
b.fun();
}
}

Derived fun() called


Observation 2

Like C++, an abstract class can contain constructors in Java. And a


constructor of an abstract class is called when an instance of an inherited
class is created. It is as shown in the program below as follows:
Example:

// Java Program to Illustrate Abstract Class


// Can contain Constructors

// Class 1
// Abstract class
abstract class Base {

// Constructor of class 1
Base()
{
// Print statement
System.out.println("Base Constructor Called");
}

// Abstract method inside class1


abstract void fun();
}

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

// Main driver method


public static void main(String args[])
{
// Creating object of class 2
// inside main() method
Derived d = new Derived();
d.fun();
}
}

Base Constructor Called


Derived Constructor Called
Derived fun() called

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:

// Java Program to illustrate Abstract class


// Without any abstract method

// Class 1
// An abstract class without any abstract method
abstract class Base {

// Demo method. This is not an abstract method.


void fun()
{
// Print message if class 1 function is called
System.out.println(
"Function of Base class is called");
}
}

// Class 2
class Derived extends Base {
// This class only inherits the Base class methods and
// properties
}

// Class 3
class Main {

// Main driver method


public static void main(String args[])
{
// Creating object of class 2
Derived d = new Derived();

// Calling function defined in class 1 inside main()


// with object of class 2 inside main() method
d.fun();
}
}

Function of Base class is called

Observation 4

Abstract classes can also have final methods (methods that cannot be
overridden)
Example:

// Java Program to Illustrate Abstract classes


// Can also have Final Methods

// Class 1
// Abstract class
abstract class Base {

final void fun()


{
System.out.println("Base fun() called");
}
}

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

Base b = new Derived();


// Calling method on object created above
// inside main method

b.fun();
}
}
}

Base fun() called

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.

// Java Program to Illustrate Abstract Class

// Main class
// An abstract class
abstract class GFG {

// Main driver method


public static void main(String args[])
{

// Trying to create an object


GFG gfg = new GFG();
}
}

Output:

Observation 6

Similar to the interface we can define static methods in an abstract class


that can be called independently without an object.

// Java Program to Illustrate


// Static Methods in Abstract
// Class Can be called Independently

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

// Main driver method


public static void main(String[] args)
{

// Calling method inside main()


// as defined in above class
Helper.demofun();
}
}

Geeks for Geeks

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");
}
}
}

public class Main {

public static void main(String args[])


{
// Instantiating the outer class
D outer = new D();

// Instantiating the inner class


D.E inner = outer.new E();
inner.myAbstractMethod();
}
}

Inside abstract method implementation

Observation 8

If a class contains at least one abstract method then compulsory that we


should declare the class as abstract otherwise we will get a compile-time
error ,If a class contains at least one abstract method then, implementation is
not complete for that class, and hence it is not recommended to create an
object so in order to restrict object creation for such partial classes we use
abstract keyword.
/*package whatever //do not write package name here */

import java.io.*;

// here if we remove the abstract


// keyword then we will get compile
// time error due to abstract method
abstract class Demo {
abstract void m1();
}

class Child extends Demo {


public void m1()
{
System.out.print("Hello");
}
}
class GFG {
public static void main(String[] args)
{
Child c = new Child();
c.m1();
}
}

Hello

Observation 9

If the Child class is unable to provide implementation to all abstract methods


of the Parent class then we should declare that Child class as abstract so
that the next level Child class should provide implementation to the
remaining abstract method.
// Java Program to demonstrate
// Observation
import java.io.*;

abstract class Demo {


abstract void m1();
abstract void m2();
abstract void m3();
}

abstract class FirstChild extends Demo {


public void m1() {
System.out.println("Inside m1");
}
}

class SecondChild extends FirstChild {


public void m2() {
System.out.println("Inside m2");
}
public void m3() {
System.out.println("Inside m3");
}
}

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();

SecondChild s = new SecondChild();


s.m1();
s.m2();
s.m3();
}
}

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

to be subclassed by another class to use its properties.

● An abstract class can be created using “abstract” keywords.

● We can have an abstract class without any abstract method.

FAQs of Abstract class

1. What is an abstract class in Java?

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.

3. What is the main advantage of abstract class?

An abstract class provides the provides of data hiding in Java.

4. Why abstract class is faster than interface?

An abstract class is faster than an interface because the interface involves a


search before calling any overridden method in Java whereas abstract class
can be directly used.

—--------------------------------------------------------------------

Difference between Abstract Class and


Interface in Java
Last Updated : 26 Jul, 2024



In object-oriented programming (OOP), both abstract classes and

interfaces serve as fundamental constructs for defining contracts. They

establish a blueprint for other classes, ensuring consistent

implementation of methods and behaviors. However, they each come with

distinct characteristics and use cases.


In this article, we will learn abstract class vs interface in Java.

Difference Between Abstract Class and Interface

Points Abstract Class Interface

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)

Methods are abstract


Can have both
Implementation by default; Java 8, can
implemented and
Method have default and
abstract methods.
static methods.

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).

Can have member Variables are


variables (final, implicitly public,
Variables
non-final, static, static, and final
non-static). (constants).

As we know that abstraction refers to hiding the internal implementation of


the feature and only showing the functionality to the users. i.e. showing only
the required features, and hiding how those features are implemented behind
the scene. Whereas, an Interface is another way to achieve abstraction in
java. Both abstract class and interface are used for abstraction, henceforth
Interface and Abstract Class are required prerequisites.

Abstract Class in Java


1. Definition:

An abstract class is a class that cannot be instantiated directly. It serves as a


blueprint for other classes to derive from.

2. Method Implementation:

An abstract class can contain both abstract methods (methods without an


implementation) and concrete methods (methods with an implementation).

3. Variables:

Abstract classes can have member variables, including final, non-final, static,
and non-static variables.

4. Constructors:

Abstract classes can have constructors, which can be used to initialize


variables in the abstract class when it is instantiated by a subclass.
Example 1:
Java
abstract class Shape {
String objectName = " ";

Shape(String name) {
this.objectName = name;
}

public void moveTo(int x, int y) {


System.out.println(this.objectName + " has been moved to x = " + x
+ " and y = " + y);
}
abstract public double area();
abstract public void draw();
}

class Rectangle extends Shape {


int length, width;

Rectangle(int length, int width, String name) {


super(name);
this.length = length;
this.width = width;
}

@Override
public void draw() {
System.out.println("Rectangle has been drawn ");
}

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

class Circle extends Shape {


double pi = 3.14;
int radius;

Circle(int radius, String name) {


super(name);
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle has been drawn ");
}

@Override
public double area() {
return (double)(pi * radius * radius);
}
}

public class Main {


public static void main(String[] args) {
Shape rect = new Rectangle(2, 3, "Rectangle");
System.out.println("Area of rectangle: " + rect.area());
rect.moveTo(1, 2);

System.out.println();

Shape circle = new Circle(2, "Circle");


System.out.println("Area of circle: " + circle.area());
circle.moveTo(2, 4);
}
}
Area of rectangle: 6.0
Rectangle has been moved to x = 1 and y = 2

Area of circle: 12.56


Circle has been moved to x = 2 and y = 4

Example 2:
// Abstract class Sunstar
abstract class Sunstar {
// Abstract method printInfo
abstract void printInfo();
}

// Employee class that extends the abstract class Sunstar


class Employee extends Sunstar {
// Implementation of the abstract method printInfo
void printInfo() {
String name = "Avinash"; // Employee name
int age = 21; // Employee age
float salary = 222.2F; // Employee salary

System.out.println(name); // Print name


System.out.println(age); // Print age
System.out.println(salary); // Print salary
}
}

// Base class to test the implementation


class Base {
public static void main(String args[]) {
Sunstar s = new Employee(); // Create an Employee object
s.printInfo(); // Call the printInfo method
}
}

Avinash
21
222.2

Interface in Java

1. Definition:

An interface is a reference type in Java, it is similar to a class, and it is a


collection of abstract methods and static constants.
2. Method Implementation:

All methods in an interface are by default abstract and must be implemented


by any class that implements the interface.From Java 8, interfaces can have
default and static methods with concrete implementations.From Java 9,
interfaces can also have private methods.

3. Variables:

Variables declared in an interface are by default public, static, and final


(constants).
Example:
interface Drawable {
void draw();
}

interface Movable {
void moveTo(int x, int y);
}

class Circle implements Drawable, Movable {


double pi = 3.14;
int radius;

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);
}
}

public class Main {


public static void main(String[] args) {
Circle circle = new Circle(2);
circle.draw();
circle.moveTo(2, 4);
}
}

Circle has been drawn


Circle has been moved to x = 2 and y = 4

Points Abstract Class Interface

Can have only abstract


methods (until Java 7),
and from Java 8, can
Can have both abstract
Type of Methods have default and static
and concrete methods
methods, and from
Java 9, can have
private methods.

Can have final,


Only static and final
Variables non-final, static, and
variables
non-static variables.
Can extend only one A class can implement
Inheritance
class (abstract or not) multiple interfaces

Cannot have
Constructors Can have constructors
constructors

Can provide the Cannot provide the


Implementation implementation of implementation of
interface methods abstract class methods

By understanding these distinctions, you can make informed decisions about


when to use abstract

classes and interfaces in Java programming.

Features of an Abstract Class in Java

An abstract class in Java is a special type of class that cannot be instantiated


directly and serves as a blueprint for other classes. It provides a way to
define a common interface or behavior that can be shared by multiple related
classes, but with specific implementations in each derived class.
Key features:
● Cannot be instantiated: Abstract classes cannot be directly

instantiated, meaning you cannot create objects of an abstract class.


● Combining Partial Implementation and Subclass Contract:

Abstract classes can contain abstract methods (methods without

implementations) that must be overridden by subclasses.

Additionally, they can have concrete methods with implementations,

allowing abstract classes to provide both a partial implementation

and a contract for subclasses to follow.

● Can contain both abstract and non-abstract methods: Abstract

classes can have both abstract and non-abstract methods.

Non-abstract methods have complete implementations and can be

called directly.

● Can have constructors: Abstract classes can have constructors that

can be called when a subclass is instantiated, allowing for

initialization of the class’s fields.

● Can have member variables: Abstract classes can have member

variables, which are variables that belong to an instance of the

class. These variables can be final, non-final, static, or non-static.

● Can be used as a base class: Abstract classes can be used as a

base class for other classes, meaning they can be inherited by other

classes. This allows for code reuse and the creation of a common

interface or behavior for related classes.


Overall, abstract classes in Java are used to define a common interface or
behavior that can be shared by multiple related classes, with specific
implementations provided by each derived class.

Features of an Interface in Java

An interface in Java is a reference type, similar to a class, that can contain


only constants, method signatures, default methods, static methods, and
nested types. Interfaces cannot contain instance fields. The methods in
interfaces are abstract by default (except for default and static methods
introduced in Java 8 and private methods in Java 9). Here are the
Key features:
● Defines a set of methods and properties: An interface defines a set

of abstract methods that any class implementing the interface must

provide implementations for. It acts as a contract that ensures

certain methods are present in the implementing class. Interfaces

can also declare constants (public static final variables).

● Provides a common protocol: Interfaces establish a common

protocol for different software components, allowing them to

communicate with each other. This ensures consistency and

interoperability across different parts of a software system.

● Supports polymorphism: Interfaces support polymorphism,

enabling objects of different classes to be treated as instances of the

interface type. As long as the objects implement the same interface,

they can be used interchangeably, promoting flexibility and

extensibility.
● Enables separation of concerns: By defining method signatures

without implementations, interfaces promote separation of

concerns. This allows different parts of a software system to be

developed independently, as long as they adhere to the interface

specifications. This decouples the implementation details from the

interface.

● Improves code reusability: Interfaces improve code reusability by

allowing different classes to implement the same interface. This

means that common functionality defined by the interface can be

reused across multiple classes, reducing code duplication and

enhancing maintainability.

● Enforces design patterns: Interfaces can enforce design patterns,

such as the Adapter pattern or Strategy pattern, by requiring certain

methods or properties to be implemented by the implementing

classes. This promotes consistent design and adherence to

established best practices.

● Facilitates testing: Interfaces facilitate testing by enabling the use

of mock objects that implement the interface. This allows software

components to be tested independently of each other, ensuring that

each component behaves correctly in isolation before integrating

them into the larger system.


● Static and Default Methods: Since Java 8, interfaces can include

default methods with implementations, which provide a way to add

new methods to interfaces without breaking existing

implementations. Interfaces can also include static methods, which

belong to the interface itself rather than any instance.

● Private Methods: Since Java 9, interfaces can also include private

methods to encapsulate shared code between default methods,

helping to avoid code duplication within the interface.

Overall, interfaces in Java are powerful tools for defining contracts and
promoting flexibility, interoperability, and maintainability in software design.

When to use what?

Consider using abstract classes if any of these statements apply to your


situation:

● 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

these related classes.

● You can define the non-static or non-final field(s) in the abstract

class so that via a method you can access and modify the state of

the object to which they belong.


● You can expect that the classes that extend an abstract class have

many common methods or fields, or require access modifiers other

than public (such as protected and private).

Consider using interfaces if any of these statements apply to your situation:

● It is a total abstraction, all methods declared within an interface

must be implemented by the class(es) that implements this

interface.

● A class can implement more than one interface. It is called multiple

inheritances.

● You want to specify the behavior of a data type without worrying

about its implementation.

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

Our aim is to understand and implement Control Abstraction in Java. Before


jumping right into control abstraction, let us understand what is abstraction.

Abstraction: To put it in simple terms, abstraction is nothing but displaying


only the essential features of a system to a user without getting into its details.
For example, a car and its functions are described to the buyer and the driver
also learns how to drive using the steering wheel and the accelerators but the
inside mechanisms of the engine are not displayed to the buyer. To read more
about Abstraction, refer here.

First of all we see one simple example of abstraction and we move to


the control abstraction in Java:

Java
abstract class gfg {
abstract void printInfo();
}

class employee extends gfg {


void printInfo() {
String name = "avinash";
int age = 21;
float salary = 22332.2F;

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

In abstraction, there are two types: Data abstraction and Control


abstraction.

Data abstraction, in short means creating complex data types but giving out
only the essentials operations.

Control Abstraction: This refers to the software part of abstraction wherein


the program is simplified and unnecessary execution details are removed.

Here are the main points about control abstraction:

● 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.

A simple algorithm of control flow:

● The resource is obtained first


● Then, the block is executed.
● As soon as control leaves the block, the resource is closed

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"); }
}

// Subclass (inherit from Vehicle)


class Car extends Vehicle {
public void VehicleSound()
{
// The body of VehicleSound() is provided here
System.out.println("kon kon");
}
}

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

Control Abstraction and Data Abstraction are two key concepts in

computer science that help simplify complex systems by hiding

unnecessary details. Let’s explain each with examples.

1. Control Abstraction

Definition:

● Control abstraction refers to the process of simplifying complex control

structures (like loops, conditionals, etc.) into simple, understandable blocks.

The goal is to hide the details of how tasks are controlled or performed,

providing a higher-level, simpler way to interact with them.

Example: Methods (functions) in programming are a good example of control

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

worrying about how the method is implemented.

Example in Java:
java

Copy code

public class Calculator {

// This is a method that abstracts away the control flow for addition

public int add(int a, int b) {

return a + b; // The internal logic is hidden

public static void main(String[] args) {

Calculator calc = new Calculator();

int result = calc.add(5, 3); // User doesn't need to know how the addition is

done internally

System.out.println(result); // Output: 8

In the example above:


● Control abstraction is used in the add() method. The internal steps of how

addition happens are abstracted away. The user simply calls add(5, 3)

without knowing the underlying implementation.

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.

Example: Classes in Object-Oriented Programming (OOP) are an example of data

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 {

// Private data, hidden from outside classes

private double balance;


// Constructor to initialize balance

public BankAccount(double initialBalance) {

this.balance = initialBalance;

// Public method to deposit money (abstracts away the internal implementation)

public void deposit(double amount) {

if (amount > 0) {

balance += amount;

// Public method to get the balance (hides internal representation of balance)

public double getBalance() {

return balance;

}
public class Main {

public static void main(String[] args) {

BankAccount account = new BankAccount(1000); // Create account with initial

balance

account.deposit(500); // Deposit money, user doesn't know how balance is

managed internally

System.out.println("Balance: " + account.getBalance()); // Output: 1500

In the example above:

● The data abstraction happens in the BankAccount class. The balance

variable is private, meaning it can't be accessed directly from outside the

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.

Comparison of Control and Data Abstraction:


Aspect Control Abstraction Data Abstraction

Focus Hides how operations are Hides how data is stored or

controlled represented

Example Functions or methods Classes, Data Encapsulation

Goal Simplify complex operations and Provide a simple way to

control flow interact with data

Real-world TV remote (pressing a button hides ATM (interface hides the

Example the complexity of controlling TV) bank’s internal processes)

Summary

● Control abstraction simplifies the way operations and control flows are

represented.

● Data abstraction simplifies how data is represented, accessed, and

manipulated.

—---------------------------------------------------------------------------------------------------

Difference Between Data Hiding and


Abstraction in Java
Last Updated : 09 Jun, 2023



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.

A real-life example of abstraction

By using ATM GUI screen bank people are highlighting the set of services
what the bank is offering without highlighting internal implementation.

Types of Abstraction: There are basically three types of abstraction

1. Procedural Abstraction
2. Data Abstraction
3. Control Abstraction

1. Procedural Abstraction: From the word itself, there are a series of


procedures in form of functions followed by one after another in sequence to
attain abstraction through classes.

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:

● Users or communities can achieve security as there are no highlights


to internal implementation.
● The enhancement will become very easy because without affecting
end users one is able to perform any type of changes in the internal
system
● It provides more flexibility to end-user to use the system very easily
● It improves the richness of application

Implementation of Abstraction: It is implemented as a class which only


represents the important traits without including background detailing.
Providing only the necessary details and hiding all its internal implementation.
Below is the java implementation of abstraction:

// Java program showing the working of abstraction

// Importing generic libraries


import java.io.*;

// Creating an abstract class


// demonstrate abstraction
abstract class Creature {

// Just providing that creatures has legs


// Hiding the number of legs
abstract void No_Of_legs();
}

// A new child class is extending


// the parent abstract class above
class Elephant extends Creature {

// Implementation of the abstract method


void No_Of_legs()
{

// Printing message of function in non abstract


// child class
System.out.println("It has four legs");
}
}

// Again a new child class is extended from parent


// Human class to override function created above
class Human extends Creature {

// Same function over-riden


public void No_Of_legs()
{

// Message printed if this function is called or


// Implementation of the abstract method
System.out.println("It has two legs");
}
}

public class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating human object showing the implementation


Human ob = new Human();

ob.No_Of_legs();

// Creating object of above class in main


Elephant ob1 = new Elephant();

// Calling the function in main by


// creating object of above non abstract class
ob1.No_Of_legs();
// Implementation of abstraction
}
}

It has two legs


It has four 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

Sample for data hiding:

class Account {

private double account_balance;

……..

…….

}
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.

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.

Concept involved in data Hiding: Getter and setter

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.

Implementation of Data Hiding:


// Java Program showing working of data hiding

// Importing generic libraries


import java.io.*;

// Class created named Bank


class Bank {
// Private data (data hiding)
private long CurBalance = 0;

// Bank_id is checked for authentication


long bank_id;
String name;

// Getter function to modify private data


public long get_balance(long Id)
{

// Checking whether the user is


// authorised or unauthorised

// Comparing bank_id of user and the given Id


// then only it will get access
if (this.bank_id == Id) {

// Return current balance


return CurBalance;
}

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

// Another class created- Employee


public class Emp {
public static void main(String[] args)
{
// Creating employee object of bank type
Bank _emp = new Bank();

// Assigning employee object values


_emp.bank_id = 12345;
_emp.name = "Roshan";

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

long emp_balance = _emp.get_balance(12345);


// As this time it is valid user it will get access

// Display commands
System.out.println("User Name"
+ " " + _emp.name);
System.out.println("Bank_ID"
+ " " + _emp.bank_id);
System.out.println("Current Balance"
+ " " + emp_balance);
}
}

User Name Roshan


Bank_ID 12345
Current Balance 10000

You might also like