The abstract keyword can be used in the declaration of classes and methods. Use of the keyword in a class declaration typically means that one or more of the methods within the class body are declared as abstract. If the keyword is left off the class declaration, and a method within the body of the class is declared using the abstract keyword, then the class is implicitly defined to be abstract. In other words, the keyword abstract need not be provided as part of the class declaration in this circumstance, and the code will compile successfully. (For readability it is recommended that abstract class declarations include the keyword to make the class intention clear.)
Classes declared to be abstract cannot be instantiated. Instead, abstract classes force the programmer to provide a body for each abstract method within a new derived class. The following example shows a simple abstract class and a class derived from it:
public abstract class FruitClass
{
public boolean isPeelable( );
.
.
.
}
public class BananaClass extends FruitClass
{
private boolean bPeel;
public boolean isPeelable( ) {
.
.
.
return bPeel;
}
}
The derived class (BananaClass) may be instantiated, and any non-abstract methods of the abstract class (FruitClass) will be inherited unless they are overridden.
Note that a class declaration cannot use abstract and final.
The abstract keyword can also be used to define methods. As already shown above, a class containing abstract methods is then also (either implicitly or explicitly) defined as abstract and must be subclassed in order to be instantiated. An abstract method cannot have the implementation defined within the abstract class. Rather, it is declared with arguments and a return type as usual, but the body that is enclosed in curly braces is replaced with a semicolon.
Consider the following example declaration of an abstract method:
abstract public int someMethod( int arg1, int arg2);
Note that a method declared with the keyword abstract cannot be declared with the keywords static, private, or final.