Abstraction In Java

Abstraction is a process of hiding the internal details and showing only the functionality to the user. In Java abstraction makes complicated systems simpler by just exposing the features and behavior that are actually required. Abstraction is a fundamental concept in object oriented programming (OOP)

lets take an example:

Abstraction is like a using a laptop without knowing the details of its internal hardware components. when you use laptop you interact with keyboard, touchpad, and screen without needing to understand the circuitry, processors and other electronic components that makes it function

Abstraction hides the internal workings of objects. which means users can’t have direct access to the implementation details This keeps data private and stops outsiders from messing with the object’s insides. Abstraction only displays relevant features to users.


Abstraction allows the user to focus on the functionality or behavior of an object rather than worrying about the complex details of how the object achieves that functionality. By hiding the implementation details, abstraction creates a clear separation between the interface (what is accessible to the user) and the implementation (how the object performs its functions).

How to achieve abstraction in Java

There are two ways to achieve abstraction in java: –

  • Abstract class (0 to100%)
  • Interface (100%)

Let’s understand these concepts in more detail.

Abstract Class in java

An abstract class is a class which is declared using abstract keyword and cannot be instantiated, meaning you cannot create objects of that class directly. abstract class can have both abstract and non abstract methods. Here abstract keyword in java is a modifier applicable for classes and methods but not for Variables.

Declaring Abstract Classes in Java

To declare an abstract class in Java, you use the abstract keyword before the class keyword in the class declaration. Here’s the syntax for declaring an abstract class:

The syntax of an abstract class is given below:

abstract class Shape {
    // Abstract method
    abstract double calculateArea();

    // Concrete method
    void display() {
        System.out.println("This is a shape.");
    }
}

As shown in the syntax of the above abstract class, we can have abstract as well as non-abstract methods in an abstract class and we used abstract keyword with class name.

Key Points to Remember about Java Abstract Class

  • To make a class abstract, you must use the keyword “abstract” before the “class” keyword.
  • Abstract classes can include both abstract methods (without implementation) and concrete methods (with implementation).
  • When you declare abstract methods in a class, any subclass must provide implementations for these methods through a process called method overriding.
  • If a class and its inheriting child class are both abstract, the child class isn’t required to implement the parent’s abstract methods.
  • If even just one method in a class is abstract, the class itself must be declared as abstract.
  • you can’t directly create objects of abstract classes. However, you can create references to abstract class types.
  • When a subclass object is created, the constructor of the abstract parent class is also invoked.
  • If you intend for a class to be inherited but not directly instantiated, include only concrete methods.
  • Abstract classes can contain final methods, which can’t be overridden by subclasses.
  • A class marked as final cannot include abstract methods, as these methods are meant to be implemented by subclasses.
  • Java doesn’t allow a class to extend multiple abstract classes. Interfaces are used for achieving multiple inheritance.:
  • when an abstract class implements an interface. In this case, the abstract class is not required to provide implementations for all the methods of the interface. Subclasses of the abstract class are then responsible for implementing the remaining methods of the interface.

We will cover abstract classes concept with rules in details in our upcoming tutorial:

Abstract Method in Java

A method without a body is known as an Abstract Method. An abstract method declared inside a abstract class with abstract keyword without any implementation. It left to the subclasses to provide their own implementation and customize the behavior of the abstract method according to their specific needs. Abstract method used to define common interface for a group of subclasses

Syntax of Abstract Methods is below:

abstract void abstractMethodName();

Here is the another basic syntax of abstract method with Abstract class:

abstract class AbstractClass {
    abstract void abstractMethod();
}

class ConcreteClass extends AbstractClass {
    @Override
    void abstractMethod() {
        // Implementation for the abstract method
    }
}

Rules of an Abstract method in Java:

  • Abstract method in Java must be declared using the abstract keyword.
  • Abstract methods must not have a body. They should end with a semicolon instead of a curly brace.
  • Abstract methods must be declared in an abstract class or interface.
  • An abstract class may or may not contain abstract methods in java.
  • All classes that extend an abstract class that has an abstract method must implement the abstract method.
  • Abstract methods can have parameters and a return type, just like any other method.
  • A class containing abstract methods should also be abstract.
  • Each method declared within an interface is automatically treated as abstract so no need to use abstract keyword with method name inside interface.

Here’s a list of modifiers that are not allowed in combination with the abstract keyword in Java:

  • final
  • abstract native
  • abstract synchronized
  • abstract static
  • abstract private
  • abstract strictfp

Interface in Java:

The interface in Java is a mechanism to achieve abstraction. When you define an interface, you’re essentially creating a set of rules that classes must follow. These rules specify the names of methods that the implementing classes must have. However, the interface doesn’t dictate exactly how these methods should work. Each class can implement these methods in its own way, using its unique logic and behavior to achieve the desired outcome.

Syntax of Interface in Java:

An interface is a fully abstract class. It includes a group of abstract methods (methods without a body) and We use the interface keyword to create an interface in Java. For example,

 interface NameOfInterface
                    {
                           // Any number of constant fields (final, static fields)
                           // Any number of abstract method declarations
                    }

Lets take an real life example to understand interface:

Think of an interface in Java as a cooking recipe shared among a group of chefs. The recipe lists the ingredients and the steps to create a dish, but it doesn’t specify how each chef should exactly chop, mix, or cook. Each chef interprets the recipe and applies their own expertise to bring out the flavors.

The below code demonstrates chefs and their cooking styles using a cooking recipe analogy:

// Define a cooking recipe interface
interface Recipe {
    void gatherIngredients(); // interface method (does not have a body)
    void cookDish(); // interface method (does not have a body)
}

// ChefA "implements" the Recipe interface
class ChefA implements Recipe {
    @Override
    public void gatherIngredients() {
        // The body of gatherIngredients() is provided here
        System.out.println("Chef A gathers fresh ingredients.");
    }

    @Override
    public void cookDish() {
        // The body of cookDish() is provided here
        System.out.println("Chef A cooks the dish with expertise.");
    }
}

// ChefB "implements" the Recipe interface
class ChefB implements Recipe {
    @Override
    public void gatherIngredients() {
        // The body of gatherIngredients() is provided here
        System.out.println("Chef B selects exotic ingredients.");
    }

    @Override
    public void cookDish() {
        // The body of cookDish() is provided here
        System.out.println("Chef B cooks the dish passionately.");
    }
}

public class ChefExample {
    public static void main(String[] args) {
        ChefA chefA = new ChefA(); // Create a ChefA object
        ChefB chefB = new ChefB(); // Create a ChefB object
        
        chefA.gatherIngredients();
        chefA.cookDish();
        
        System.out.println("---------------------------");
        
        chefB.gatherIngredients();
        chefB.cookDish();
    }
}

Output:

Chef A gathers fresh ingredients.
Chef A cooks the dish with expertise.
---------------------------
Chef B selects exotic ingredients.
Chef B cooks the dish passionately.

Explanation:

  1. Recipe Interface:
    • An outline called Recipe is created with two steps: gatherIngredients() and cookDish().
    • No specific actions are defined; it’s like saying “We need to gather ingredients and cook, but we won’t say how.”
  2. ChefA and ChefB Classes:
    • ChefA and ChefB classes implement the Recipe outline.
    • Each chef fills in the recipe’s steps with their own style:
      • ChefA gathers fresh ingredients and cooks with expertise.
      • ChefB selects exotic ingredients and cooks passionately.
  3. Main Class: ChefExample
    • The program’s entry point.
    • Creates instances of ChefA and ChefB.
    • Shows each chef following the recipe: gathering ingredients and cooking.
    • Illustrates how different chefs give unique flavors to the same recipe.

In essence, this code paints a picture of chefs using the same recipe but adding their own twists to it, all through the magic of Java’s interfaces and classes.

Rules of Interface in Java:

  • Interfaces cannot be declared as private or protected. Only public and default modifiers are allowed in interface
  • Every variable of an interface is by default public static and final while every method of an interface is by default public and abstract.
  • Interface variables must be initialized with some value at the time of declaration.
  • Class implementing an interface cannot change the value of variable declared in the interface since they are declared as final by default.
  • Class implementing an interface must implement all the methods of that interface, otherwise the class must be declared as abstract.
  • While implementing the method of an interface in a class, it’s visibility(access modifier) can not be reduced. Reducing the visibility will result in compilation error, so it must have public access modifier in class as well.
  • An interface can extend another interface but it cannot implement it. Only classes can implements interfaces.
  • multiple inheritance can be achieved with interfaces, because the class can implement multiple interfaces.
  • If a class implements two interfaces which have same method name, then the implementation of same name method once is enough.
  • A class cannot implement two interfaces that have methods with same name but different return type.
  • Interfaces define method signatures (names, parameters, return types), but not method bodies. Implementing classes must provide the actual method implementations.
  • An interface can have another interface inside it is called Nested Interface
  • interface methods are implicitly public and abstract. You don’t need to explicitly use these modifiers when declaring methods in an interface.
  • From java 8 onward an interface can have default and static methods with body.
  • An interface cannot contain a constructor because it cannot be used to create objects

We will cover all the concepts about interface and given rules here in detail in our upcoming tutorial on interface

Conclusion:

In this tutorial, we have discussed abstraction in Java and how it can be achieved by using abstract classes and interfaces. We also covered some basic concepts about abstract classes, abstract methods, and interfaces with real-life examples We will cover abstract classes and interface rules in more detail in our upcoming tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *