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 classes are useful when you want to create a generic type that is used as the superclass for two or more subclasses, but the superclass itself doesn’t represent an actual object. If all employees are either salaried or hourly, for example, it makes sense to create an abstract Employee class and then use it as the base class for the SalariedEmployee and HourlyEmployee subclasses.

CrossRef.eps For more information, see extends Keyword and Inheritance.

Here are a few additional details regarding abstract classes:

check.png Not all the methods in an abstract class have to be abstract. A class can provide an implementation for some of its methods but not others. In fact, even if a class doesn’t have any abstract methods, you can still declare it as abstract. (In that case, though, the class can’t be instantiated.)

check.png A private method can’t be abstract. All abstract methods must be public.

check.png A class can’t be both abstract and final.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset