3. 方法动态绑定
Java在运行期间判断所引用对象的实际类型,根据实际的类型调用其相应的方法实例:
package com.geek99.demo;
public class Test {
public static void main(String[] args) {
Pet cat = new Cat();
Pet dog = new Dog();
Person per = new Person();
per.care(cat);
per.care(dog);
}
}
interface Pet{
public void run();
}
class Person {
public void care(Pet p){
p.run();
}
}
class Cat implements Pet{
@Override
public void run() {
System.out.println("cat run...");
}
}
class Dog implements Pet{
@Override
public void run() {
System.out.println("dog run...");
}
}
原文出处:http://geek99.com/node/433#
该博客教程视频地址:http://geek99.com/node/1629
转载于:https://blog.51cto.com/8785849/1413374