abstract keyword

Class Syntax

>>-+--------+-abstract-class-Identifier-+-------------------+->
   '-public-'                           '-extends-ClassType-'

>-+------------------------------+-ClassBody-><
  '-implements-InterfaceTypeList-'

Method Syntax

>>-+-----------+-abstract-ResultType-Identifier->
   +-public----+
   '-protected-'

>-(-+---------------------+-)-;-><
    '-FormalParameterList-'

Description
The abstract keyword is used to create abstract classes and methods. Abstract classes cannot be instantiated and their purpose is to provide common information for subclasses. Abstract classes can contain anything that a normal class can contain, that is, class and instance variables, as well as methods and constructors with any modifiers.  Only abstract classes may have abstract methods. If a class that is not abstract contains an abstract method, then a compilation error occurs. A class has abstract methods if any of the following is true:

If you declare private, static, and final methods to be abstract, a compilation error occurs. It is impossible to override a private method, thus an abstract private method could never be implemented.  Static methods are always available, so there must be an implementation; a static abstract method could never have an implementation.  A final method cannot be overridden, so there could never be an implementation of a final abstract method.

An abstract class can override an abstract method by providing another abstract method declaration.  This can provide a place to put a documentation comment, or to declare a more limited set of checked exceptions that can be thrown.

Examples
In the following example, the abstract class MyAbstractClass has one regular method and one abstract method.  The concrete class MyConcreteClass inherits from MyAbstractClass and provides an implementation for abstractMethod.

public abstract class MyAbstractClass {
    public void regularMethod() {
        abstractMethod();
    }
    
    protected abstract void abstractMethod();
}
public class MyConcreteClass extends MyAbstractClass {
    protected void abstractMethod() {
        // does something interesting
    }
}

The following code fragments show legal and illegal uses of the MyAbstractClass and MyConcreteClass classes.

// ILLEGAL. Compiler error.
MyAbstractClass abstractClass = new MyAbstractClass();

// LEGAL.
MyConcreteClass concreteClass = new MyConcreteClass();

// ILLEGAL. Protected method.
concreteClass.abstractMethod();
// LEGAL. Ordinary method.
concreteClass.regularMethod();

ngrelr.gif (548 bytes)
Syntax diagrams
class keyword
extends keyword
final keyword
implements keyword
private keyword
public keyword
static keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.