Jump to content
Wikibooks The Free Textbook Project

Java Programming/Keywords/abstract

From Wikibooks, open books for an open world

abstract is a Java keyword. It can be applied to a class and methods. An abstract class cannot be directly instantiated. It must be placed before the variable type or the method return type. It is recommended to place it after the access modifier and after the static keyword. A non-abstract class is a concrete class. An abstract class cannot be final .

Only an abstract class can have abstract methods. An abstract method is only declared, not implemented:

Computer code Code listing 1: AbstractClass.java
publicabstractclass AbstractClass{
// This method does not have a body; it is abstract.
publicabstractvoidabstractMethod();

// This method does have a body; it is implemented in the abstract class and gives a default behavior.
publicvoidconcreteMethod(){
System.out.println("Already coded.");
}
}

An abstract method cannot be final , static nor native . Because an abstract class can't directly be instantiated, you must either instantiate a concrete sub-class or you instantiate the abstract class by implementing its abstract methods alongside a new statement:

Example Code section 1: Abstract class use.
AbstractClassmyInstance=newAbstractClass(){
publicvoidabstractMethod(){
System.out.println("Implementation.");
}
};

A private method cannot be abstract .

AltStyle によって変換されたページ (->オリジナル) /