Lesson: Overriding

Overview: 
Explore method overriding when extending classes.
Objectives: 

Understand how subclass methods can override methods in the superclass.

Content: 

We have seen how we can extend a class to have additional fields and methods and build a more specialized object. But what if we want to change the behavior of one of the superclass methods? we can do this with Overriding.

Overriding is simply defining a method in the new (sub) class that has the same signature (method name and parameter list) of a method in the super (parent) class. This method in the subclass is said to override the same method in the superclass. When you call this method on a subclass instance, you will execute  the code defined in the subclass. Note that if you call the method on an instance of the superclass, you will execute the code defined in the superclass.

Lets look at an example. Say we have a base class of Animal and subclasses of Dog and Cat. All three have the same method, whatIsMyName():

This code will print out:

I am an Animal named roger
I am a Dog named rover
I am a Cat and I am an Animal named kitty

So each class has the same method signature whatIsMyName() but the result of the method is different for each class. This concept is called polymorphisim. Note in the Cat version of whatIsMyName() we called the superclass method of the same name with the super keyword. So we can replace superclass functionality or modify the result of the superclass method in a subclass.

Here is a video with more about Overriding.

Here is the example above in CodingGround. Give it a try!

 

Navigation: