4.代码
Master类
package code08_三大特征.test08_多态的实现;
/*
* 主人类
*/
public class Master {
String name;
public Master() {
}
public Master(String name) {
super();
this.name = name;
}
// 与宠物玩耍
public void play(Pet pet) {// 将父类的引用作为方法的形参,减少代码,更具有扩展性
pet.play();
}
// 喂养宠物
public void feed(Pet pet, Food food) {
System.out.println("给" + pet.name + "喂养" + food.name);
}
}
Dog类
package code08_三大特征.test08_多态的实现;
/*
* 狗狗类
*/
public class Dog extends Pet {
String hobby;
public Dog() {
super();
}
public Dog(String name, String sex, String hobbby) {
super(name, sex);
this.hobby = hobby;
}
@Override
public void show() {
System.out.println("这是一只狗狗,名叫:" + name);
}
@Override
public void play() {
System.out.println(name + "正在接飞盘---------");
}
}
Cat类
package code08_三大特征.test08_多态的实现;
/*
* 猫猫类
*/
public class Cat extends Pet {
String breed;
public Cat() {
super();
}
public Cat(String name, String sex, String breed) {
super(name, sex);
this.breed = breed;
}
@Override
public void show() {
System.out.println("这是一只猫,名叫:" + name);
}
@Override
public void play() {
System.out.println(name + "正在走猫步--------");
}
}
Food类
package code08_三大特征.test08_多态的实现;
/*
* 食物类
*/
public class Food {
String name;//食物名称
}
Bone类
package code08_三大特征.test08_多态的实现;
public class Bone extends Food {
}
Fish类
package code08_三大特征.test08_多态的实现;
public class Fish extends Food{
}
Test类
package code08_三大特征.test08_多态的实现;
public class Test {
public static void main(String[] args) {
Master master = new Master("唐伯虎");
Dog dog = new Dog("旺财", "公", "游戏");
master.play(dog);
Bone bone = new Bone();
bone.name = "骨头";
master.feed(dog, bone);
Cat cat = new Cat("咪咪", "母", "波斯猫");
master.play(cat);
Fish fish = new Fish();
fish.name = "鱼";
master.feed(cat, fish);
}
}
领养:
package code08_三大特征.test08_多态的实现;
import java.util.Scanner;
/*
* 领养宠物
*/
public class 练习2_多态 {
public static void main(String[] args) {
showMenu();
}
/*
* 显示主菜单
*/
public static void showMenu() {
Scanner input = new Scanner(System.in);
System.out.println("欢迎来到宠物店");
System.out.println("请选择您要领养的宠物(1.狗狗2.猫咪):");
int choice = input.nextInt();
Pet pet = getPet(choice);
pet.show();
pet.play();
}
/*
* 根据选择获取相应的宠物
*/
public static Pet getPet(int choice) {
Pet pet = null;
switch (choice) {
case 1:
pet = new Dog("旺财", "公", "游戏");
break;
case 2:
pet = new Cat("猫咪", "母", "波斯猫");
break;
default:
System.out.println("输入有误没有对应的宠物");
}
return pet;
}
}
小声bb:重新看了前面的代码,发现很多次复制笔记时{}
会弄错,之前为了方便,包名用了汉字,所以尽量都没有复制包名,以至于总是多一个}
,太粗心啦,大家不要像我一样啊.