Inheritance is implemented in Java as the simple extension of the methods/fields of a superclass or interface using the extends
or implements
keywords, respectively. Either way, you have access in the subclass to the public and protected data members of the superclass, and when acting on the subclass from the outside, only the public data members.
Taking your example, you could have definitions of several classes:
class Animal {
private int location;
public Animal() {
location = 0;
}
public void move() {
location += 10;
}
public int getLocation() {
return location;
}
}
class Dog extends Animal {
@Override
public void move() {
setLocation(getLocation() + 5);
}
}
/*
* The @Override flag is optional, but I prefer to put it there
* to ensure that I am actually overriding a method or implementing
* a method from an interface.
*/
class Cat extends Animal {
@Override
public void move() {
setLocation(getLocation() + 15);
}
}
So Dog
and Cat
both extend Animal - this is an inheritance relationship.
Polymorphism is something totally different. According to Wikipedia:
The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior.
In simple English terms, this just means taking the same idea or action and implementing it differently based on the specific type of object that it is. In code:
public static void main(String[] args) {
Animal animalArray = {
new Animal(),
new Cat(),
new Dog()
};
for (Animal a : animalArray) {
a.move();
}
System.out.println("Animal location: " + animalArray[0].getLocation());
System.out.println("Cat location: " + animalArray[1].getLocation());
System.out.println("Dog location: " + animalArray[2].getLocation));
}
This produces the output:
Animal location: 10
Cat location: 15
Dog location: 5
Note that each object, the Animal
, the Cat
, and the Dog
are all accessed as Animal
s. This is possible because every class is or extends Animal
, and each class will therefore always have the public method move()
, which is simply redefined in some cases.
Interfaces work on the same philosophy; if a class extends an interface, it can be guaranteed to have some implementation of every method defined in the interface, and it can thus be used in terms of the methods that the interface implements.