Java Abstraction

java

In Java, abstraction is a technique for hiding the implementation details of a class and exposing only the necessary functionality to the users of the class. It allows you to create a simplified interface for a complex system and separates the interface from the implementation, so that the implementation can be changed without affecting the users of the interface.

There are two main ways to implement abstraction in Java: abstract classes and interfaces.

An abstract class is a class that contains one or more abstract methods, which are methods that do not have an implementation and must be implemented by any concrete (non-abstract) subclass of the abstract class. An abstract class can also contain concrete (non-abstract) methods, which do have an implementation.

Here’s an example of an abstract class in Java:

abstract class Animal {
  public abstract void makeSound();
  
  public void eat() {
    System.out.println("Eating...");
  }
}

In this example, the Animal class is an abstract class that contains an abstract method called makeSound() and a concrete method called eat(). Any concrete subclass of the Animal class must implement the makeSound() method, but can use the implementation of the eat() method provided in the Animal class.

An interface is a collection of abstract methods that define a set of behaviors that a class must implement. A class can implement multiple interfaces, but it can only extend one superclass.

Here’s an example of an interface in Java:

interface Animal {
  void makeSound();
  void eat();
}

class Cat implements Animal {
  @Override
  public void makeSound() {
    System.out.println("Meow");
  }
  
  @Override
  public void eat() {
    System.out.println("Eating...");
  }
}

In this example, the Animal interface defines the makeSound() and eat() methods that a class must implement. The Cat class implements the Animal interface and provides implementations for the makeSound() and eat() methods.