已经学习了一段时间,需要对前期的知识进行一个总结,所以准备选择一道题.
题目:
狗有单独行为看家,猫单独行为玩
分析题目 : 一共三个类,
类 | 属性 | 行为 | 吃的东西something |
人People | 年龄 姓名 | 喂养keepPet | |
狗 Dog | 年龄,颜色 | 吃eat 看家lookHome | 骨头 |
猫Cat | 年龄,颜色 | 吃eat 玩play | 鱼 |
人 类:
属性年龄和姓名私有化,
喂养两个动物,狗和猫都有吃东西行为
简化 :有两个keepPet 代码,可以运用多态进行简化,创建一个父类,将dog和cat的喂养方法放置一起,构造方法和get和set方法折叠起来了
动物类
将cat和dog放在一起可以创建一个新的类 :动物类,有他们共有的属性,年龄,颜色和eat吃的行为
,eat吃的行为可以不用输出,则可以将动物类Animal类设为一个抽象类。get set 和构造方法折叠起来了。
狗类 :
狗类继承动物类,重写吃的抽象方法eat,并写独属于自己的方法looHome();
猫类 ;
猫类继承动物类,重写动物类方法eat ,然后有自己的方法玩play()
测试类 :
在main函数中创建人对象people people = new people();
创建狗对象时需要向上转型 :Animal dog = new Dog();
创建狗对象时需要向上转型 : Animal cat = new Cat();
此时输出结果为 : 与问题答案相同
测试2 :
狗和猫有自己独有行为lookHome和playMouse;
如果直接用Animal对象调用会报错,无法调用本类的非重写行为.需要强制向下转型
此时结果输出为
完成题目问题
附上完整代码
package dayda;
class people {
private String name;
private int age;
public people() {
super();
}
public people(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void keepPet(Animal animal, String something) {
if (animal instanceof Dog) {
System.out.println(
"年龄为" + age + "岁的" + name + "" + "养了一只" +
animal.getColor() + "颜色的" + animal.getAge() + "岁的狗");
animal.eat(something);
} else if (animal instanceof Cat) {
System.out.println(
"年龄为" + age + "岁的" + name + "" + "养了一只" +
animal.getColor() + "颜色的" + animal.getAge() + "岁的猫");
animal.eat(something);
}
}
}
abstract class Animal {
private String color;
private int age;
public Animal() {
super();
}
public Animal(String color, int age) {
super();
this.color = color;
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public abstract void eat(String something);
}
class Cat extends Animal {
@Override
public void eat(String something) {
System.out.println(getAge()+"岁的"+getColor()+"颜色的猫眯着眼睛侧着头吃"+something);
}
public void playMouse() {
System.out.println("汤姆在捉杰瑞");
}
}
class Dog extends Animal {
@Override
public void eat(String something) {
// TODO Auto-generated method stub
System.out.println(getAge()+"岁的"+getColor()+"颜色的狗两只前"
+ "腿死死的抱住"+something+"猛吃");
}
public void lookHome() {
System.out.println("狗在看家");
}
}
public class Demo1 {
public static void main(String[] args) {
people people = new people();
people.setName("老王");
people.setAge(30);
Animal dog = new Dog();
dog.setColor("黑");
dog.setAge(2);
people.keepPet(dog, "骨头");
System.out.println("==============");
people person1 = new people();
people.setName("老李");
people.setAge(25);
Animal cat = new Cat();
cat.setColor("灰");
cat.setAge(3);
people.keepPet(cat, "鱼");
System.out.println("=======向下转型====");
Dog dog2 = (Dog) dog;
dog2.lookHome();
Cat cat2 = (Cat)cat;
cat2.playMouse();
}
}