好的,以下是一个使用多态实现上述需求的Java代码示例: ```java // 定义抽象类Friend abstract class Friend { abstract void comeFrom(); // 抽象方法,表示从哪里来 } // 定义继承类ChineseFriend,继承自Friend抽象类 class ChineseFriend extends Friend { private String foodPreference = "四川菜"; private String martialArts = "太极拳"; @Override void comeFrom() { System.out.println("小明的好朋友王小强从中国来"); } // 定义方法,表示喜欢吃四川菜和练太极拳 public void showPreference() { System.out.println("王小强喜欢吃" + foodPreference + ",喜欢练" + martialArts); } } // 定义继承类AmericanFriend,继承自Friend抽象类 class AmericanFriend extends Friend { private String foodPreference = "比萨"; private String sport = "橄榄球"; @Override void comeFrom() { System.out.println("小明的好朋友约翰从美国来"); } // 定义方法,表示喜欢吃比萨和打橄榄球 public void showPreference() { System.out.println("约翰喜欢吃" + foodPreference + ",喜欢打" + sport); } } // 创建小明的变量和方法 public class Main { public static void main(String[] args) { Friend[] friends = new Friend[2]; // 创建两个Friend对象数组 friends[0] = new ChineseFriend(); // 创建ChineseFriend对象并赋值给friends数组的第一个位置 friends[1] = new AmericanFriend(); // 创建AmericanFriend对象并赋值给friends数组的第二个位置 for (Friend friend : friends) { // 遍历friends数组并访问每个朋友的偏好和方法comefrom()方法 friend.comefrom(); // 输出"从哪里来"信息 friend.showPreference(); // 输出各自偏好的食物或运动和练习方法的信息 } } } ``` 上述代码中,我们首先定义了一个抽象类Friend和一个继承自Friend的ChineseFriend类和一个AmericanFriend类。在每个类的构造函数中,我们可以看到它们的特性和喜好(比如喜欢吃川菜、太极拳,或者喜欢吃比萨、橄榄球等)。我们使用数组存储这些Friend对象,并使用多态调用它们的`comefrom()`方法表示来访的朋友,同时通过多态调用每个对象的`showPreference()`方法显示它们的偏好。这样就实现了不同国家的朋友来访并显示他们各自喜好的需求。 [2024-04-25 15:48:13 | AI写代码神器 | 586点数解答]