Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The abstract keyword

The abstract keyword: The abstract keyword marks an incomplete class that cannot be instantiated with new, or a bodyless method that a concrete subclass must implement.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

abstract

The abstract keyword marks an incomplete class that cannot be instantiated with new, or a bodyless method that a concrete subclass must implement.

Use an abstract class when shared state and implementation accompany required extension points; consider an interface for a contract without that state.

The first concrete subclass must implement every inherited abstract method; a method cannot be both abstract and final, private, or static.

An abstract class may have constructors, fields, and concrete methods and may declare no abstract method at all; its constructor runs through a subclass super call.

Concrete Square implements area, so inherited label prints square:16 and the polymorphic reference reports type=Square.

Examples

public class Main {
  abstract static class Shape { final String name; Shape(String n){name=n;} abstract int area(); String label(){return name+":"+area();} }
  static final class Square extends Shape { final int side; Square(int s){super("square");side=s;} @Override int area(){return side*side;} }
  public static void main(String[] args){ Shape shape=new Square(4); System.out.println(shape.label()); System.out.println("type="+shape.getClass().getSimpleName()); }
}

Result

square:16
type=Square

Concrete Square implements area, so inherited label prints square:16 and the polymorphic reference reports type=Square.

Sources