This is the lecture note of CS61B - Lecture 8.
A Real Problem
Recall SLList
and AList
we have implemented until now. They exactly have many same methods (signatures), although their data structures under the hood are totally different.
Now, suppose we’re writing a library to manipulate lists of words. We might want to write a function that finds the longest word from a list of words.
1 | public class WordUtils { |
Read the code above, I think you should understand why there is an error when calling longest
method on an AList. Now, what should we do if we want the longest
method can also handle AList beautifully?
To sovle this problem, you should know the knowledge of interface
and inheritance
.
Hypernyms, Hyponyms, and Interface Inheritance
- Hypernyms(上位词) represent abstraction.
- Hyponyms(下位词) represent details.
Java can help us build this hierarchy.
Now, turn back to the previous problem. We can solve it now.
1 | public class WordUtils { |
Overriding vs. Overloading
##Interface Inheritance
In the last section, we said that subclass must override all methods of interface, otherwise it will fail to compile. In fact, this is not accurate.
1 | public interface List61B<Item> { |
If you don’t like the default method, you absolutely can override it. For example, the default print
method is inefficient for SLList
, so we override it:
1 | public interface SLList<Item> implements List61B<Item> { |
Static and Dynamic Type, Dynamic Method Selection
To wrap up above materials, let's do a puzzle.
Suppose we have classes defined below. Try to predict the results.
1 | interface Animal { |
Add annotation to the above code, and also give the answer.
1 | public interface Animal { |
The shocking answer is the last one, i.e. a.flatter(d);
. Why?
There are some rules that you should apply when solving such problems.
- At compile time: we determine the signature S of the method to be called.
- S is decided using ONLY static types
- At runtime: the dynamic type of the invoking object uses its method with this exact signature S.
- By involing object, we mean the object whose method is invoked.
So,
- since
a
hasAnimal
static type,a.greet(d)
will call the default interface methodgreet
; - although
a
hasAnimal
static type, thesniff
method has be overriden inDog
class, soa.sniff(d)
will call the dynamic type methodsniff
; - since
d
hasDog
static type,d.praise(d)
will call the methodpraise
fromDog
class; - notice
praise
method is not overriden, it's just overload, so sincea
hasAnimal
static type,a.praise(d)
will call the default interface methodpraise
;
🦔 Related Slides: link here
Real World
Finally, let's go back to the real world.
We will use the Java's built-in List interface and several implementations, e.g. ArrayList, LinkedList, Stack, Vector etc. in our future works.
1 | import java.util.List; |
Reference: LINK