Inheritance II: Extends, Casting, Higher Order Functions
10.1 Implementation Inheritance: Extends
extend 语法:
public class RotatingSLList<Blorp> extends SLList<Blorp>{
public void rotateRight() {
Blorp oldBack = removeLast();
addFirst(oldBack);
}
}
Constructor Behavior
extend 的子类需要在构造函数中调用父类的构造函数,通过super()
. 如果省略了 java 会帮忙自动调用。
public VengefulSLList() {
deletedItems = new SLList<Item>();
}
public VengefulSLList() {
super();
deletedItems = new SLList<Item>();
}
如果子类构造函数需要调用父类带参数的构造函数,那么这时候必须主动调用super(...)
, 否则 java 只会自动调用不带参数的super()
.
public VengefulSLList(Item x) {
super(x);
deletedItems = new SLList<Item>();
}
public VengefulSLList(Item x) {
deletedItems = new SLList<Item>();
}
10.2 Encapsulation
Module: A set of methods that work together as a whole to perform some task or set of related tasks. A module is said to be encapsulated if its implementation is completely hidden, and it can be accessed only through a documented interface.
10.3 Casting
Java 中的每个变量都有一个静态类型。这是在声明变量时指定的类型,并在编译时进行检查。每个变量也有一个动态类型;此类型在实例化变量时指定,并在运行时检查。
Compile-Time Type Checking and Expressions
SLList<Integer> sl = new VengefulSLList<Integer>();
VengefulSLList<Integer> vsl = new SLList<Integer>();
第一行 compile time type 右边是 VengefulSLList 左边是 SLList, VengefulSLList 是 SLList, 所以 compile check pass.
第二行 compile time type 右边是 SLList 左边是 VengefulSLList, SLList 不 VengefulSLListst, 所以 compile check fail.
public static Dog maxDog(Dog d1, Dog d2) { … }
Poodle frank = new Poodle("Frank", 5);
Poodle frankJr = new Poodle("Frank Jr.", 15);
Dog largerDog = maxDog(frank, frankJr);
Poodle largerPoodle = maxDog(frank, frankJr);
maxDog() 返回的 compile time type 是 Dog.
在最后一行会报错,因为 Dog 不是 Poodle.
casting
java 支持强制类型转换,来改变 compile time type。
10.4 Higher order Function in java
java7 包括之前的版本,变量不能是函数指针。
需要用 interface 来实现 HoF:
public interface IntUnaryFunction {
int apply(int x);
}
public class TenX implements IntUnaryFunction {
public int apply(int x) {
return 10 * x;
}
}
public class HoFDemo {
public static int do_twice(IntUnaryFunction f, int x) {
return f.apply(f.apply(x));
}
public static void main(String[] args) {
System.out.println(do_twice(new TenX(), 2));
}
}