8.1 向上转型
向上转型:把对某个对象的引用视为对其基类型的引用
public class Person {
public void eat() {
System.out.println("Person eat...");
}
}
public class Animal extends Person {
public void eat() {
System.out.println("Animal eat...");
}
}
public class Man extends Person {
public void eat() {
System.out.println("Man eat...");
}
}
public class Login {
public static void loginVerify(Person person) { // 以父类接受,不用向下面一样为每一种类型写方法
person.eat();
}
// public static void loginVerify(Animal animal) {
// animal.eat();
// }
// public static void loginVerify(Man man) {
// man.eat();
// }
public static void main(String[] args) {
Man man = new Man();
Animal animal = new Animal();
loginVerify(man); // Man eat...
loginVerify(animal); // Animal eat...
}
}
8.2 前期绑定与后期绑定
绑定:将一个方法与调用主体关联起来。
前期绑定:在程序执行前进行绑定
后期绑定:也叫做动态绑定、运行时绑定。在运行时根据对象的类型进行绑定。
Java中除了static和final方法(包括private)之外都是后期绑定
static方法:与类相关,与单个的对象无关。
final方法:导出类无法覆写。
private方法:导出类无法继承,所以“覆写”相当于重新写一个方法。
public class A {
public static void f1() {
System.out.println("f1");
}
public final void f2() {
System.out.println("f2");
}
private void f3() {
System.out.println("f3");
}
}
public class B extends A {
public static void main(String[] args) {
A.f1();
A a = new B();
a.f2();
// f3调不到
}
}
域不是多态的
8.4 用继承进行设计
在建立新类时,应首先选择组合。组合不会强制我们进入继承的层次结构中,而且组合更加灵活。
向下转型
Person person = new Man();
person.eat();
//person.fly(); Person类没有的的方法不能调用
((Man) person).fly(); // 向下转型,可能会报类型转换异常