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");
}
}
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024