< Java Programming < Keywords

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:

Code listing 1: AbstractClass.java
1 public abstract class AbstractClass {
2     // This method does not have a body; it is abstract.
3     public abstract void abstractMethod();
4  
5     // This method does have a body; it is implemented in the abstract class and gives a default behavior.
6     public void concreteMethod() {
7         System.out.println("Already coded.");
8     }
9 }

An abstract method cannot be final, static nor native. Either you instantiate a concrete sub-class, either you instantiate the abstract class by implementing its abstract methods alongside a new statement:

Code section 1: Abstract class use.
1 AbstractClass myInstance = new AbstractClass() {
2     public void abstractMethod() {
3         System.out.println("Implementation.");
4     }
5 };

A private method cannot be abstract.

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.