0

超类中的方法适用于java中的所有子类......如果子类有自己独立的方法,我怎样才能让它工作......

class  Polymorphism3 {

 public static void main(String[] args) {
            // note how these are all considered objects of type Animal by Java
            Animal[] a = new Animal[4];
            a[0] = new Mouse();
            a[1] = new Bird();
            a[2] = new Horse();
            a[3] = new Animal();            
            for (int i=0;i<4;i++) {
                a[i].pullTail();                
            }           

//...       


class Animal {
    public void pullTail() {
        System.out.println("I don't know what to say.");
    }
}

class Mouse extends Animal {
    public void pullTail() {
        System.out.println("fart");
    }
}

class Bird extends Animal {
    public void pullTail() {
        System.out.println("tweet");
    }

    public void fly() {
        System.out.println("flap");
    }
}

class Horse extends Animal {
    public void pullTail() {
        System.out.println("neigh");
    }
}
4

2 回答 2

1

如果这是关于无法实例化嵌套类:您需要一个封闭类的对象:

public class Polymorphism3 {
    public static void main(String[] args) {
        // note how these are all considered objects of type Animal by Java
        Animal[] a = new Animal[4];
        Polymorphism3 poly = new Polymorphism3();
        a[0] = poly.new Mouse();
        a[1] = poly.new Bird();
        a[2] = poly.new Horse();
        a[3] = poly.new Animal();
        for (int i = 0; i < 4; i++) {
            a[i].pullTail();
        }
    }

    class Animal {
        public void pullTail() {
            System.out.println("I don't know what to say.");
        }
    }

    class Mouse extends Animal {
        public void pullTail() {
            System.out.println("fart");
        }
    }

    class Bird extends Animal {
        public void pullTail() {
            System.out.println("tweet");
        }

        public void fly() {
            System.out.println("flap");
        }
    }

    class Horse extends Animal {
        public void pullTail() {
            System.out.println("neigh");
        }
    }
}
于 2013-03-02T00:25:28.603 回答
1

如果未在 Animal 中声明,则无法使其工作。
唯一的方法是将Animal转换为Bird,例如

((鸟)a[1]).fly();

您也可以从 Bird 的 putTail 实现中调用它。

于 2013-03-02T00:16:46.620 回答