Abstraction in Java explained with example.

 Abstraction in Java is the process of hiding the implementation details and exposing only the necessary information to the user. It is one of the core concepts of object-oriented programming and is used to create a simplified version of an object or class, allowing the user to interact with it in a more intuitive and user-friendly way.

Abstraction in java

One of the most common examples of abstraction in Java is using an interface. An interface defines a set of abstract methods (methods without a body) that a class implementing the interface must implement. For example:


interface Shape {
  void draw();
}

class Circle implements Shape {
  public void draw() {
    System.out.println("Drawing a circle");
  }
}

class Square implements Shape {
  public void draw() {
    System.out.println("Drawing a square");
  }
}

In this example, we have an interface Shape with an abstract method draw(). The Circle and Square classes implement the Shape interface and provide their own implementation of the draw() method.

Now, consider the following code:


Shape s = new Circle();
s.draw();  //Output : Drawing a circle

Here, we create a Shape reference variable s and assign it an instance of Circle. When we call the draw() method on s, it calls the draw() method of the Circle class. However, we do not need to know the implementation details of the draw() method in the Circle class, all we need to know is that s is a Shape and it can be drawn.

This is an example of abstraction, where the user is only exposed to the necessary information (the Shape interface) and the implementation details are hidden.

Another example of abstraction in Java is using an abstract class. An abstract class is a class that cannot be instantiated, but it can be inherited. An abstract class can have both abstract methods (methods without a body) and concrete methods (methods with a body). For example:


abstract class Shape {
  abstract void draw();

  void display(){
    System.out.println("Displaying the shape");
  }
}

class Circle extends Shape {
  public void draw() {
    System.out.println("Drawing a circle");
  }
}

In this example, the Shape class is an abstract class with an abstract method draw() and a concrete method display(). The Circle class extends the Shape class and provides its own implementation of the draw() method.

In summary, abstraction in Java allows us to hide the implementation details of an object or class, exposing only the necessary information to the user. It helps to reduce the complexity of the code and make it more user-friendly, making it easier to understand and use.