Inheritance Note

2018-08-08  本文已影响0人  Kulbear

Hypernym and Hyponym

We use the word hyponym for the opposite type of relationship.

Hypernyms and hyponyms comprise a hierarchy.

Interface

Overriding vs. Overloading

Interface Inheritance

Specifying the capabilities of a subclass using the implements keyword is known as interface inheritance.

Implementation Inheritance: Default Methods

Use the default keyword to specify a method that subclasses should inherit from an interface.

Static and Dynamic Type, Dynamic Method Selection

Every variable in Java has a “compile-time type”, a.k.a. “static type”.

Variables also have a “run-time type”, a.k.a. “dynamic type”.

Suppose we call a method of an object using a variable with:

Then if Y overrides the method, Y’s method is used instead.

  • If we have a variable has static type X and dynamic type Y, then if Y overrides the method, Y's method is used instead.
  • At compile time, the compiler will verify X has a method that can handle the given parameter. If multiple methods can handle, it records the most specific one.
  • At runtime, if Y overrides the recorded signature, use the overridden method.

Implementation Inheritance: Extends

When a class is a hyponym of an interface, we used implements. If you want one class to be a hyponym of another class, you use extends.

Type Checking and Casting

Expressions have compile-time types:

Java has a special syntax for specifying the compile-time type of any expression.

Subtype Polymorphism

Polymorphism: “providing a single interface to entities of different types”

Interfaces and Abstract Classes

implements and extends can be used to enable interface inheritance and implementation inheritance.

Interfaces may combine a mix of abstract and default methods.

Abstract classes are an intermediate level between interfaces and classes.

Abstract classes are often used as partial implementations as interfaces.

Interfaces:

Abstract classes:

Generalized Comparison

Comparables

The industrial strength approach: Use the built-in Comparable interface.

Already defined and used by tons of libraries. Uses generics.

public interface Comparable<T> {
     public int compareTo(T obj);
} 
public class Dog implements Comparable<Dog> {
    public int compareTo(Dog uddaDog) {
        return this.size - uddaDog.size;
    }

Comparators

In some languages, we’d write two comparison functions and simply pass the one we want :

The standard Java approach: Create sizeComparator and nameComparator classes that implement the Comparator interface.

public interface Comparator<T> {
    int compare(T o1, T o2);
}

public class Dog implements Comparable<Dog> {
  private String name;
  private int size;
 
  public static class NameComparator implements Comparator<Dog> {
    public int compare(Dog d1, Dog d2) {
        return d1.name.compareTo(d2.name);
    }
  }
  ...
}
上一篇 下一篇

猜你喜欢

热点阅读