Abstraction in java with example

Abstraction is a concept of exposing only essential details and hiding implementation details.

You can achieve abstraction using two ways in java.

  1. Abstract class(0 to 100% abstraction)
  2. Interface (100% abstraction)

For example:

When you search for any text on google, you just type text in text area and click on search button. What happens behind the scenes, how google search algorithm works, you might not be aware of that.

Abstract class in java

An abstract class is the class which is declared abstract and can have abstract or non abstract methods.  It should be extended by child class and should implement abstract method.

Abstract method in java:

Abstract method is the method which do not have implementation i.e. it does not have any body.

Interface in java:

Interface is generally used to provide contract for class to implement. Interface do not have implementation of any method.A class implements an interface, thereby inheriting the abstract methods of the interface. So it is kind of signing a contract, you agree that if you implement this interface, then you have to use its methods.It is just a pattern, it can not do anything itself.
Example of interface in java:

Real life Example of abstraction in java:

Lets say we have Sport as interface. Now it’s implementation will be provided by classes called “Cricket” and “Football”.In real scenario, end user will not aware of implementation class and object of implementation class can be provided by factory method. Factory method can be used to create object of implementation class based on some criterion.
Let’s create an interface called Sport.java.

Create class named “Cricket”

Create class named “Football”

Create main class named “SportInterfaceMain”

When you run above program, you will get below output:

Playing cricket
Playing football

That’s all about abstraction in java.

No Responses

Add Comment