Abstract Class

An abstract class is a class that contains one or more abstract methods, which are simply method declarations without a body — that is, without executable code that implements the class or method. An abstract method is like a prototype for a method, declaring the method’s return type and parameter list but not providing an actual implementation of the method.

You can’t instantiate an abstract class. However, you can create a subclass that extends an abstract class and provides an implementation of the abstract methods defined by the abstract class. You can instantiate the subclass.

To create an abstract method, you specify the modifier abstract and replace the method body with a semicolon:

public abstract return-type method-name(parameter-list);

Here’s an example:

public abstract int hit(int batSpeed);

To create an abstract class, you use abstract on the class declaration and include at least one abstract method. For example:

public abstract class Ball

{

public abstract int hit(int batSpeed);

}

You can create a subclass from an abstract class like this:

public class BaseBall extends Ball

{

public int hit(int batSpeed)

{

// code that implements the hit method goes here

}

}

When you subclass an abstract class, the subclass must provide an implementation for each abstract method in the abstract class. In other words, it must override each abstract method.

tip.eps Abstract ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.