Lecture 8: Inheritance, Implements

9/14/2020

The Desire for Generality

AList and SList

Using ALists and SLists: WordUtils.java

Method Overloading in Java

public static String longest(AList<String> list) { ... } public static String longest(SLList<String> list) { ... }

The Downsides

Hypernyms, Hyponyms, and Interface Inheritance

Hypernyms

Hypernym and Hyponym

Simple Hyponymic Relationships in Java

Step 1: Defining a List61B.java

public interface List61B<Item> { public void addLast(Item x); public Item getLast(); public Item get(int i); public int size(); public Item removeLast(); public void insert(Item x, int position); public Item getFirst(); }

Step 2: Implementing the List61B Interface

public class AList<Item> implements List61B<Item> { ... } public class SLList<Item> implements List61B<Item> { ... }
public class WordUtils { public static String longest(List61B<String> list) { ... } }

Overriding vs. Overloading

Method Overriding

public class Math { public int abs(int a) public double abs(double a) }

Optional Step 2B: Adding the @Override Annotation

public class AList<Item> implements List61B<Item> { @Override public Item getItem(int a) { ... } }

Interface Inheritance

Interface Inheritance

Copying the Bits

public static void main(String[] args) { List61B<String> someList = new SLList<>(); someList.addFirst("elk"); }

Implementation Inheritance: Default Methods

Implementation Inheritance

public interface List61B<Item> { public void addLast(Item x); public Item getLast(); public Item get(int i); public int size(); public Item removeLast(); public void insert(Item x, int position); public Item getFirst(); /** Prints out the entire List. */ default public void print() { for (int i = 0; i < size(); i += 1) { System.out.print(get(i) + ' '); } System.out.println(); } }

Is the print() method efficient?

Overriding Default Methods

Overriding Default Methods

public class SLList<Item> { @Override public void print() { for (Node p = sentinel.next; p != null; p = p.next) { System.out.print(p.item + ' '); } } }

Dynamic Method Selection

Static Type vs. Dynamic Type

Dynamic Method Selection For Overridden Methods

More Dynamic Method Selection, Overloading vs. Overriding

The Method Selection Algorithm

Is a vs Has a, Interface vs Implementation Inheritances

Interface vs. Implementation Inheritance

Dangers of Implementation Inheritance