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:
- 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.
javaabstract class MyAbstractClass {
abstract void myAbstractMethod(); // Abstract method
void myConcreteMethod() {
// Concrete method
}
}
- 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
class MyConcreteClass extends MyAbstractClass {abstract class MyAbstractClass {
abstract void myAbstractMethod();
}
// Error: MyConcreteClass is not abstract and does not override abstract method
}To fix this error, either provide an implementation for
myAbstractMethod
inMyConcreteClass
or declareMyConcreteClass
as abstract.
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.