Java-Abstract Classes

Abstract Classes

A class for which cannot create objects is called an abstract class. An abstract class is to be extended and then instantiated. Some of the methods in an abstract class may be declared as abstract methods. Such an abstract method consists of a declaration without any body, as shown below:

All abstract methods that are declared in an abstract class should be implemented by the class that extends this abstract class. As we may recall, the abstract classes cannot be instantiated. A class that can be instantiated is known as the concrete class. We know that the subclasses of an abstract class can be instantiated. Therefore, they are all concrete classes. They implement the functionality that is declared by the abstract method.

In the following program, one abstract method named topSpeed( ) is declared within the abstract class BigCat. The class Lion extends the class BigCat and provides one implementation for the topSpeed( ) method. Similarly the class Tiger extends the class BigCat and provides another implementation for the topSpeed( ) method.

Since each subclass provides a different form of the topSpeed( ) method, this is a nice example of run-time polymorphism. Within the main( ) method in the class Javaapp, objects of the subclasses Lion and Tiger are created. Then the topSpeed( ) method is invoked with reference to each one of these two objects.

Program

final2

Program Source

abstract class BigCat {
    
    abstract void topSpeed();
}

class Lion extends BigCat {
    
    void topSpeed()
    {
        System.out.println("Lion : 81 km/h");
    }
}

class Tiger extends BigCat {
    
    void topSpeed()
    {
        System.out.println("Tiger : 65 km/h");
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Lion li = new Lion();
        Tiger ti = new Tiger();
        li.topSpeed();
        ti.topSpeed();
    }
}

2 thoughts on “Java-Abstract Classes

Leave a Comment