Java Polymorphism Example

Java polymorphism is the ability that a parent class can be extended by differnt child classes, and each child class can have the same inherited method from the parent class as other child classes, but the same method can act differntly with differnt child class. The example demonstrated here is a parent class Animal with 3 child classes Deer, Wold and Lion. They all inherited the abstract method describe(), but this method describe the child class accordingly, depends on if the class is a Deer or a Wolf or a Lion.

The Animal class
[code language=”java”]
public abstract class Animal {

private String breed;

// constructor method
public Animal(String b)
{
breed=b;
}

// regular getter method
public String getBreed()
{
return breed;
}

// abstract method has no implementation
public abstract void describe();

}
[/code]

The Deer class
[code language=”java”]
public class Deer extends Animal{

private String name;

public Deer(String nm)
{
//calls super class constructor
super("deer");
name=nm;
}

//required method,
//overrides the one in its parent class
@Override
public void describe() {
System.out.print("A "+getBreed());
System.out.print(" named ");
System.out.println(name);
}

}
[/code]

The Wolf class
[code language=”java”]
public class Wolf extends Animal{

private String name;

public Wolf(String nm)
{
//calls super class constructor
super("wolf");
name=nm;
}

//required method,
//overrides the one in its parent class
@Override
public void describe() {
System.out.print("A "+getBreed());
System.out.print(" named ");
System.out.println(name);
}

}
[/code]

The Lion class
[code language=”java”]
public class Lion extends Animal{

private String name;

public Lion(String nm)
{
//calls super class constructor
super("lion");
name=nm;
}

//required method,
//overrides the one in its parent class
@Override
public void describe() {
System.out.print("A "+getBreed());
System.out.print(" named ");
System.out.println(name);
}

}
[/code]

The AnimalIdentifier class to test the polymorphism
[code language=”java”]
public class AnimalIdentifier {

public static void main(String args[])
{
//animal reference
Animal animalRef;

//constructing objects deer, wolf and lion
Deer deer = new Deer("Sophie");
Wolf wolf = new Wolf("Bran");
Lion lion = new Lion("Leon");

//assign each animal to animalRef,
//then calls the describe method.
animalRef = deer; animalRef.describe();
animalRef = wolf; animalRef.describe();
animalRef = lion; animalRef.describe();

return;
}

}
[/code]

The output

    A deer named Sophie
    A wolf named Bran
    A lion named Leon

Search within Codexpedia

Custom Search

Search the entire web

Custom Search