好久没有来更新博客了,最近在学习的过程中,发现有段代码执行结果很有趣,所以就记录下来,希望大家可以使用下面的代码自己来运行,看看运行结果是怎么样的,根据运行的结果来思考下,为什么会是这样?
// 入口
public class MainDemo {
public static void main(String[] args) {
Person person = new ZhangSan();
Food food = new Fruit();
person.eat(food);
person.eat(new Fruit());
}
}
// 定义食物接口
public interface Food {
}
// 定义水果继承食物
public class Fruit implements Food {
}
// 定义人类
public abstract class Person {
public void eat(Food food) {
System.out.println("每个人都需要吃食物");
}
public void eat(Fruit fruit) {
System.out.println("有的人喜欢吃水果");
}
}
// 定义张三继承人类
package com.java.demo;
public class ZhangSan extends Person {
public void eat(Fruit fruit) {
System.out.println("有的人喜欢吃水果");
}
}
上述的代码已经都贴完整了,现在大家可以思考下,执行后的结果会是什么?
大家可以将自己思考的思路可以留言在博客下,便于大家一起讨论学习!