objects first with java a practical introduction using bluej method overriding 2.0
TRANSCRIPT
Objects First With JavaA Practical Introduction Using BlueJ
Method overriding
2.0
2
media-v2
3
Conflicting outputCD: A Swingin' Affair (64 mins)* My favourite Sinatra album Frank Sinatra Tracks: 16 DVD: O Brother, Where Art Thou? (106 mins) The Coen brothers’ best movie! Joel & Ethan Coen
title: A Swingin' Affair (64 mins)* My favourite Sinatra album
title: O Brother, Where Art Thou? (106 mins) The Coen brothers’ best movie!
What we want
What we now have
4
The problem
• The print method in Item only prints the common fields.
• Inheritance is a one-way street:– The superclass knows nothing about
its subclass’s fields.
5
The solution: overriding• Superclasses and their
subclasses can define methods with the same name.
• We shall see how this can be used.
6
Method lookup
No inheritance.The method is selected.
7
Method lookup
Inheritance but no overriding. The inheritance hierarchy is ascended, searching for a match.
8
Method lookup
Overriding. The Subclass method overrides the superclass version.
9
Method lookup summary
• The variable is accessed.• The object stored in the variable is found.• The class of the object is found.• The class is searched for a method match.• If no match is found, the superclass is
searched.• This is repeated until a match is found.• Overriding methods take precedence.
10
Super call in methods
• Overridden methods are hidden ...• ... but we often still want to be able
to call them.• An overridden method can be called
from the method that overrides it.– super.methodName(...)– Compare with the use of super in
constructors.
11
Calling an overridden method
public class CD{ ... public void print() { super.print(); System.out.println(" " + artist); System.out.println(" Tracks: " + numberOfTracks); } ...}
12
Review
• Methods can be overridden in a subclass
• Overriding methods take precedence
• Superclass methods can be called using the keyword super