Abstraction in Java

Shubham Dadasaheb Sawant
2 min readJan 20, 2022

--

Abstraction:

Process of exposing all necessary details and hiding the unwanted

Real life example:

We all are familiar with the car example. That the driver knew only the essential details required for him. For example, if the driver knows pressing the accelerator the car will move forward rather than how many strokes are working or how much is the speed of strokes or to which part the accelerator pedal is connected .

So in short driver is exposed to only necessary details

This is called abstraction

How to achieve abstraction:

  1. Using abstract class (0 to 100% abstraction may be achieved)
  2. Using interfaces (100% abstraction is achieved)

Abstract class:

  1. Abstract class is a class whose objects are not created
  2. Abstract class can have abstract methods or may not
  3. Abstract class can have concrete methods/ non- abstract methods.
  4. Recommended — if class doesn’t have abstract method don’t make class as abstract
  5. A class which is not abstract cannot have abstract methods
  6. Using abstract class we can achieve 0 to 100 % abstraction due to presence of concrete classes
  7. Abstract class can have static, final methods too
  8. Default constructor is always present in abstract class

If we don’t write constructor in abstract class JVM creates a default constructor

Counter question: why abstraction does not allow object creation

=> as abstract class may contain abstract methods where the implementation code is not present in that class. So even if the objects are created calling such methods will be of no use

Counter question: can abstract class have only concrete methods

=> yes

Syntax:

abstract class Test{

// class body

}

We cannot create object of abstract class

Counter question: why by default or user defined constructor is mandatory?

=>

If abstract class contains private variables how this variables can be instantiated

This is achieved by use of constructor for eg

===> 2

NOTE: to print a in main() method we need to make variable as public

DRY APPROACH (Dont repeat yourself)

Advantages:

  1. Clean code , no duplicate data
  2. Security

When i will use abstract class instead of interface

=> to achieve abstraction at 0 to 100% i will use abstract class

=> when we need to declare some concrete classes in abstract class we go with abstract class and not interface

--

--

Shubham Dadasaheb Sawant
Shubham Dadasaheb Sawant

No responses yet