Download presentation
Presentation is loading. Please wait.
Published byDinah Hancock Modified over 9 years ago
1
Objects First With Java A Practical Introduction Using BlueJ Method overriding 2.0
2
2 media-v2
3
3 Conflicting output CD: 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
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
5 The solution: overriding Superclasses and their subclasses can define methods with the same name. We shall see how this can be used.
6
6 Method lookup No inheritance. The method is selected.
7
7 Method lookup Inheritance but no overriding. The inheritance hierarchy is ascended, searching for a match.
8
8 Method lookup Overriding. The Subclass method overrides the superclass version.
9
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
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
11 Calling an overridden method public class CD {... public void print() { super.print(); System.out.println(" " + artist); System.out.println(" Tracks: " + numberOfTracks); }... }
12
12 Review Methods can be overridden in a subclass Overriding methods take precedence Superclass methods can be called using the keyword super
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.