When Does The Compiler Insist That The Class Must Be Abstract

If one or more methods of the class are abstract. If class inherits one or more

abstract methods from the parent abstract class and no implementation is provided for

that method If class implements an interface and provides no implementation for

those methods.

In Java, a class is marked as abstract when it contains one or more abstract methods. An abstract method is a method without a body, i.e., it is declared without implementation. The purpose of abstract classes and methods is to provide a way to define a common interface for a group of related classes while allowing each class to provide its own implementation.

Here are some scenarios where the compiler insists that a class must be abstract:

  1. Abstract Method in a Class:
    • If a class contains at least one abstract method, the class must be declared as abstract. Otherwise, the compiler will generate an error.
    java
    abstract class MyAbstractClass {
    abstract void myAbstractMethod(); // Abstract method
    void myConcreteMethod() {
    // Concrete method
    }
    }
  2. Inheriting from an Abstract Class:
    • If a subclass extends an abstract class that has abstract methods, the subclass must either provide concrete implementations for those abstract methods or be declared as abstract itself.
    java
    abstract class MyAbstractClass {
    abstract void myAbstractMethod();
    }
    class MyConcreteClass extends MyAbstractClass {
    // Error: MyConcreteClass is not abstract and does not override abstract method
    }

    To fix this error, either provide an implementation for myAbstractMethod in MyConcreteClass or declare MyConcreteClass as abstract.

java
abstract class MyAbstractClass {
abstract void myAbstractMethod();
}
abstract class MyConcreteClass extends MyAbstractClass {
// No error now, as MyConcreteClass is declared abstract
}

So, in summary, the compiler insists that a class must be abstract when it contains abstract methods, or when it inherits from an abstract class without providing concrete implementations for all the abstract methods.