Skip to main content
Published on

abstract in Java

Share:

Introduction

abstract is a modifier in Java that is primarily used in object-oriented programming contexts. It plays a crucial role in the development of modular and flexible systems.

What is abstract?

In Java, abstract is used to indicate that:

  1. A class cannot be directly instantiated.
  2. A method has no body and must be implemented in a subclass.

Why use abstract Classes and Methods?

  1. To Emphasize Design: Abstract classes are often used to define a template or design for other classes.
  2. Polymorphism: It facilitates polymorphism, since derived classes can have different implementations of the abstract methods.
  3. Avoid Accidental Object Creation: Since abstract classes cannot be instantiated, they prevent the accidental creation of objects.

Difference between abstract and Interface

  • Methods and Variables: While an interface can only contain method signatures, an abstract class can contain both complete and abstract methods.
  • State Variables: Abstract classes can contain state variables, while interfaces cannot.
  • Multiple Inheritance: Java does not support multiple inheritance of classes, but allows a class to implement multiple interfaces.

Illustrating with Code

Abstract classes and methods are used when a common base is needed, but we do not want that base to be instantiated:

package com.caffeinealgorithm.programaremjava;

import java.util.ArrayList;
import java.util.List;

public class Abstract {
  public void Run() {
    // ClassX.informationX();
    var instance = new ClassY();
    instance.informationY();

    /*
      Country: Portugal
      Country: Brazil
      Country: Spain
      Country: France
      Country: Italy
      Country: Australia
      Country: India
    */
  }
}

abstract class ClassX {
  public static String community = "Caffeine Algorithm";
  public static List<String> countries = new ArrayList<>();

  public static void informationX() {
    for (char character : community.toCharArray())
      System.out.printf("Character: %c\n", character);
  }

  public abstract void informationY();
}

class ClassY extends ClassX {
  public void informationY() {
    countries.add("Portugal");
    countries.add("Brazil");
    countries.add("Spain");
    countries.add("France");
    countries.add("Italy");
    countries.add("Australia");
    countries.add("India");

    for (String country : countries)
      System.out.printf("Country: %s\n", country);
  }
}

In this example, ClassX is abstract, which means it cannot be instantiated, but ClassY (a derived class) can.

Conclusion

The abstract modifier is a valuable tool in a Java developer's arsenal. It promotes solid design practices, helping developers create more robust and maintainable systems.

Happy coding!