day6_test1_inheritance

类图

代码

Pet类

package org.lanqiao.com;

public class Pet {
    private String name ;
    private String sex;
    private String kind;
    private int age;

    {
        this.name = "未命名";
    }

    public Pet(String kind) {
        this.kind =kind;
    }

    protected void eat(String food) {
        System.out.println(this.name + "正在吃" + food);
    }

    protected String bark() {
        return name +"在叫";
    }

    protected void sleep() {
        System.out.println(name + "正在睡觉");
    }

    protected void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }
    public String getSex() {
        return sex;
    }
    public String getKind() {
        return kind;
    }
    public int getAge() {
        return age;
    }
}

Cat类:

package org.lanqiao.com;

public class Cat extends Pet{

	public Cat(String kind) {
		super(kind);
	}

	@Override
	protected String bark() {
		return super.bark() + "喵喵";
	}

	public void catchMouse() {
		System.out.println(this.getName() + "在抓老鼠");
	}
}

Dog类:

package org.lanqiao.com;

public class Dog extends Pet {

	public Dog(String kind) {
		super(kind);
	}
	protected void watchHome() {
		System.out.println(getName() +"正在看家");
	}
	@Override
	protected String bark() {
		return getName() +"正在叫:汪汪";
	}
}

Master类:

package org.lanqiao.com;

public class Master {
	public static void main(String[] args) {
		Pet dog = new Dog("哈士奇");
		dog.setName("奥特曼");
		dog.eat("骨头");
		System.out.println(dog.bark());
		((Dog)dog).watchHome();
		System.out.println(dog.bark());
		Pet pet = new Pet("wu");

		Pet cat = new Cat("狸花猫");
		cat.setName("小怪兽");
		Master master =new Master();
		master.feed(cat);

	}

	public void feed(Pet pet) {
		pet.bark();
		if(pet instanceof Dog){
			((Dog)pet).eat("骨头");
		}else{
			((Cat)pet).eat("鱼");
		}
	}
}


运行结果:

posted @ 2021-01-12 18:49  zzz2077  阅读(47)  评论(0编辑  收藏  举报