日期:2014-05-20  浏览次数:20711 次

关于多态~~
谁有关于多态的较好的例子呀···我看得晕这的··先谢谢啦··哈

------解决方案--------------------
class Animal {
private String name;
Animal(String name) {
this.name=name;
}

public void enjoy(){
System.out.println("叫声...");
}
}

class Cat extends Animal {
private String eyesColor;
Cat(String n,String c) {
super(n);
eyesColor = c ;
}
public void enjoy() {
System.out.println("猫叫...");
}
}

class Dog extends Animal {
private String furColor;
Dog(String n,String c) {
super(n);
furColor = c;
}
public void enjoy() {
System.out.println("狗叫...");
}
}

class Lady {
private String name;
private Animal pet;
Lady(String name,Animal pet) {
this.name = name; 
this.pet = pet;
}
public void myPetEnjoy() {
pet.enjoy();//只有运行的时候,才知道调用的是哪个动物的 'enjoy()' 方法
}
}

public class Test {
public static void main(String args[]) {

Cat c = new Cat("mimi","blue");
Dog d = new Dog("didi","black");

Lady l1 = new Lady("mary",c);
Lady l2 = new Lady("linda",d);
l1.myPetEnjoy();
l2.myPetEnjoy();
}
}
------解决方案--------------------
这个是最基础的多态了
Java code

enum Noto{
    MIDOLE_C,C_SHARP,B_FLAT;
}



class Instrument{
    public void play(Noto n){
        System.out.println("Instrumen.play()");
    }
}

class Wind extends Instrument{
    public void play(Noto n){
        println("Wind.play()"+n);
    }
}

public class Music{
    public static void tune(Instrument i){
        i.play(Noto.MIDOLE_C);
    }
    public static void main(String[] args){
        Wind flute = new Wind();
        tune(flute);
    }
}