Java abstract Modifier
Defining Abstract Methods and Abstract Classes with the abstract Modifier
An abstract method is a method that has no body and consists only of a signature, such as the method name, arguments, and return value. It is defined by adding the abstract modifier. Since it cannot be used as-is, it must be overridden in a subclass. An abstract method can be seen as a mechanism for declaring functionality that subclasses must implement.
A class that contains an abstract method is called an abstract class, and the abstract modifier must be specified.
For example, the following is an example of the ModAbstractChild class inheriting the abstract class ModAbstract.
ModAbstract.java
package com.devkuma.basic.modifier;
public abstract class ModAbstract {
abstract void test();
}
ModAbstractChild.java
package com.devkuma.basic.modifier;
public class ModAbstractChild extends ModAbstract {
void test() { /* ...specific processing...*/ }
}
If you comment out the void test() method in the ModAbstractChild class, a compile error occurs in the class. When inheriting an abstract class, the subclass must override all abstract methods.
Like an interface, it is a mechanism for forcing a subclass to implement specific functionality, but it differs in that it can have an implementation1. On the other hand, because it is a class, multiple inheritance is not allowed. In general, interfaces are used first, and abstract classes are used when there is a concern for common functionality.
-
Since Java SE 8, interfaces can also have default implementations. ↩︎