In the previous lesson you learnt about inheritance.
Overriding
The zoo would like to know which animal types are endangered, even though most types in the zoo are not. Add the following method within the Animal class:
public boolean isEndangered() {
return false;
}
Note that for getter methods that return a boolean value the Java convention is to prefix the method name with is rather than get.
The above method takes a default view; each animal is not endangered. Remember, each subclass automatically inherits this method, and in the case of monkeys and penguins invoking the isEndangered() method will correctly return false. However, lions are endangered, so Java allows you to override its code to do something different.
Insert the following method in the Lion class:
public boolean isEndangered() {
return true;
}
You will notice a small glyph to the left of the method declaration line in NetBeans which is a warning message. If you hover your mouse over it, you will see an @Override Annotation. Click on the glyph and then click the message which subsequently appears. You should see the following line inserted above the method:
@Override
public boolean isEndangered() {
return true;
}
This is known as an annotation and exists to remind the reader that this method overrides a method defined in a superclass. Including annotations is optional but recommended.
You can now invoke the isEndangered() method on any type of animal, and it will return false for each type except Lion objects.
boolean b1 = animal1.isEndangered(); // should return false boolean b2 = animal2.isEndangered(); // should return true boolean b3 = animal3.isEndangered(); // should return false boolean b4 = animal4.isEndangered(); // should return false
Overriding produces an example of polymorphism. This refers to the capability of an object of a particular type to take the most appropriate action in response to a request, and which may be different to the action taken by an object of a different type to the same request. In the above example, a Lion object responds to isEndangered() in a different way to a Monkey object.
In the next lesson you will learn about abstract classes and methods.
Comments