How do I create and implement abstract class?

Abstract class is a class that have one or more methods declared, but not defined. Abstract class cannot have instances. This class uses in inheritance to take advantage of polymorphism. To declare that a class is abstract, use the abstract keyword in front of the class keyword in the class definition.

Methods in abstract class that have no definition are called abstract methods. The declaration for an abstract method ends with a semicolon and you specify the method with the abstract keyword to identify it as such. The implementation is left to the sub classes.

package org.kodejava.example.fundamental;

public abstract class Animal {
   private String species;

    public Animal(String species){
        this.species = species;
    }

    public abstract void makeASound();

    public String getSpecies(){
        return species;
    }

    public static void main(String[] args) {
        Animal pig = new Pig("Warthog");
        pig.makeASound();
    }
}

The Pig class extends the Animal class. Because the Animal class contains an abstract method makeASound() the Pig class must implements this method or else the Pig will also become an abstract class.

package org.kodejava.example.fundamental;

public class Pig extends Animal {

    public Pig(String species) {
        super(species);
    }

    @Override
    public void makeASound() {
        System.out.println("oink oink");
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply