Java Reference
In-Depth Information
The concept of polymorphism is a result of inheritance and implementing interfaces:
A child class takes on the form of its parent class.
A class takes on the form of its implemented interfaces.
This section discusses how to use polymorphism in your code. We also discuss
the casting of references, the instanceof operator, polymorphic parameters, and
heterogeneous collections.
Understanding Polymorphism
To understand how polymorphism works in Java, let's look at an example of a class that
extends another class and implements an interface. Suppose we have the following Pet class
to represent the parent class of various types of pets:
public class Pet {
private String name;
private int age;
public Pet(String name, int age) {
this.name = name;
this.age = age;
}
public void eat() {
System.out.println(name + “ is eating”);
}
}
In addition, suppose we have the following interface named Mammal to represent the
behaviors of mammals:
public interface Mammal {
public void breathe();
}
The following Cat class both extends Pet and implements the Mammal interface:
public class Cat extends Pet implements Mammal {
public Cat(String name, int age) {
super(name, age);
}
public void breathe() {
Search WWH ::




Custom Search