Day8实验

Day8## 实验4整理的部分题

【练习题】1.多态练习

1.定义一个Animal父类,方法有eat();

2.定义三个子类;Cat,Dog,Eagle;

3.利用多态性

定义一个Animal类型的变量a,并将不同子类的实例赋给a;

调用eat();观察结果后,并理解多态

4.思考,如果a的引用指向一个Cat,如何调用Cat的新增方法;

public class Animal {

public void eat(){

    System.out.println("吃东西");

}

}

public class Cat extends Pet {

public void eat(){

    System.out.println("zhe shi zi lei - cat");

}

public void ccc(){



}

}

public class Dog extends Pet {

public void eat(){

    System.out.println("zhe shi zi lei - dog");

}

public void aaa(){



}

}

public class Eagleextends Pet
{

public void eat(){

    System.out.println("zhe shi zi lei - eagle");

}

public void bbb(){



}

}

Animal a = new Dog();

a.aaa();

【练习题】2.多态练习

定义一个Animal类,方法有sing方法,定义这个类的三个子类(Dog,Cat,Bird),分别重写这个方法。利用多态,定义一个Animal类型的对象,Animal a;分别引用三个子类的对象,调用sing方法。为每个子类,增加额外的方法。通过此例,练习upCast,downCast,及instanceof操作符。

public class Animal {

public void eat(){

    System.out.println("吃东西");

}

}

public class Dog extends Pet {

public void eat(){

    System.out.println("zhe shi zi lei - dog");

}

public void aaa(){



}

}

Dog d = new Dog();

System.out.println(d instanceof Animal);

【练习题】3.多态练习

模拟天天酷跑游戏;

定义一个(宠物)Pet类,类中有属性name,方法是follow(跟随);再定义三个子类,Cat,Dog,Eagle,分别重写follow方法;

再定义一个Hero类,这个类中有两个属性name和Pet类型的pet,一个方法run(),再定义两个构造方法,Hero(String name,);Hero(String name,Pet pet);

run()方法的代码是Hero跑,并且他的宠物也跟着跑;

编写测试类来操作Hero

public class Pet {

private String name;

public void follow(){

    System.out.println("zhe shi fu lei - animal");

}

}

public class Cat extends Pet {

public void eat(){

    System.out.println("zhe shi zi lei - cat");

}

public void ccc(){



}

}

public class Dog extends Pet {

public void eat(){

    System.out.println("zhe shi zi lei - dog");

}

public void aaa(){



}

}

public class Eagle extends Pet
{

public void eat(){

    System.out.println("zhe shi zi lei - eagle");

}

public void bbb(){



}

}

public class Hero {

private String name;

private Pet pet;



public Hero(String name) {

    this.name = name;

}



public Hero(String name, Pet pet) {

    this.name = name;

    this.pet = pet;

}



public void run(){

    System.out.println(this.name+"pao");

    pet.follow();

}

}

Pet p = new Dog();

Hero h = new Hero("妲己",p);

h.run();

Demo d = new Demo();

你可能感兴趣的:(Day8实验)