Created: 2023-09-03 18:02
Status: #concept
Subject: Programming
Tags: Java Java Class Abstraction Inheritance Polymorphism Java Interface

Java Abstract Class

An abstract class acts like an ordinary class, but we cannot directly instantiate objects with it, we must first create a subclass that extends it.

  • it may or may not contain abstract Methods which has a Function Prototype which still needs to be implemented by the subclass.
  • we can still define methods with a function body if we do not use the abstract keyword.
  • Generally, abstract classes are used in situations where the concept that the class represents is not a clear independent concept.

Differences with Java Interfaces

The greatest difference between Java Interfaces and abstract classes is that abstract classes can contain;

Abstract Classes Interfaces
By using extends keyword a class can inherit another class, or an interface can inherit other interfaces By using implements keyword a class can implement an interface
It is not compulsory that subclass that extends a superclass override all the methods in a superclass. It is compulsory that class implementing an interface has to implement all the methods of that interface.
Only one superclass can be extended by a class. A class can implement any number of an interface at a time.
Any number of interfaces can be extended by interface. An interface can never implement any other interface.

Example

public abstract class Operation {

    private String name;

    public Operation(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public abstract void execute(Scanner scanner);
}

The abstract class Operation works as a basis for implementing different actions. For instance, you can implement the plus operation by extending the Operation class in the following manner.

public class PlusOperation extends Operation {

    public PlusOperation() {
        super("PlusOperation");
    }

    @Override
    public void execute(Scanner scanner) {
        System.out.print("First number: ");
        int first = Integer.valueOf(scanner.nextLine());
        System.out.print("Second number: ");
        int second = Integer.valueOf(scanner.nextLine());

        System.out.println("The sum of the numbers is " + (first + second));
    }
}

References