
Abstract Methods and Classes
An abstract class is a class that has been explicitly designated as such; it may or may not have abstract methods. Although abstract class objects cannot be created, they may be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void add(int X, int Y);
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.
However, if it does not, then the subclass must also be declared abstract
.
If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class className { // declare fields // declare nonabstract methods abstract void methodName(); }
In this example, the abstract class "Vehicle" has just one abstract method called "start." The Car and Bike class provides its implementation.
2. Car Class: Extends Vehicle, which has the abstract method start.
The car class overrides the method start because cars start with buttons.
3. Bike class: extends Vehicle (an abstract class) and overrides the abstract method start ().
Since a bike starts with a kick and a button, the Bike class overrides the start() method.
4. Display class: The Display class has a method called "print" that includes a vehicle reference. As a variable
5. Main class: Car and bike objects were created in the main class.
Here, we make a new object called Display.
The print method is referenced by the passing car and bike.
6. Output