Abstraction in Java

Abstraction is a way to hide the implementation details and show only the functionality. Java provides two tools for abstraction :

  1. Abstract Classes and Methods
  2. Interfaces

1. Abstract Classes and Methods

Abstract class : A class that has abstract qualifier in its declaration is called abstract class. It can have both abstract and concrete methods.

Abstract method : A method that has been declared but not implemented is called an abstract method. abstract keyword is used to declare an abstract method.

A class containing an abstract method must be declared abstract.

1.1 Uses of Abstract classes

  • It can be used to define a generic interface for all the classes that subclass it.
  • It can be used to achieve runtime polymorphism.

1.2 An example

Abstract classes are subclasser responsibility. i.e an abstract class has to be subclassed and all abstract methods inside it must be implemented before the class can be used to create objects.

Output :

Visit abstract classes and methods in java to know more about them.

2. Interfaces

A class interface can be abstracted fully from its implementation by using the interface keyword. You can specify what a class must do, but not how it does it.

Once an interface is defined, it can be implemented by any number of classes.

2.1 An Example

Output :

Visit interfaces in Java to know more about them.

3. Miscellaneous Topics

3.1 Abstract Classes vs Interfaces

Both abstract classes and interfaces work towards common goal to abstract details and only expose the interface to a class. But they have some differences as well. Visit abstract classes vs interfaces in Java to know about it in detail.

3.2 Encapsulation vs Data Abstraction

Sometimes people get confused in these two features of OOP.

  • Abstraction deals with design issues while Encapsulation solves implementation issues.
  • Abstraction hides the interal implementation details and only provides the interface for interaction. Encapsulation groups together data and the methods that act on it.
  • Abstraction deals with detail hiding while Encapsulation deals with data hiding.

3.3 Advantages of Abstraction

  • It helps to reduce the complexity of design.
  • It also helps to avoid code duplication and promotes code reuse.
  • It hides away the implementation of the features, so malicious attacks targeted at the implementation are reduced.