该程序应该单独调用每个子类的funFact,但是,只能从funFact类调用Mammal方法。我究竟做错了什么?

 public class MammalFacts{
        public static class Mammal{
            public static String funFact(){
                return "If you are reading this, there's a 70% chance you're a mammal";
            }//end funFact

        }//end mammal
        public static class Primate extends Mammal{
            public static String funFact(){
                return "All primates can fly";
            }
        }//end Primate
        public static class Monkey extends Primate{
            public static String funFact(){
                return "Monkies will rule the earth someday";
            }
        }
        public static void main(String[]args){
            Mammal[]i = new Mammal[3];
            i[0] = new Mammal();
            i[1] = new Primate();
            i[2] = new Monkey();

            for(int c = 0; c < i.length; c++){
                System.out.println(i[c].funFact());
            }
        }//end of main
    }//end MammalFacts

最佳答案

funFact是静态的。覆盖不适用于静态方法。

从所有方法中删除static关键字(无论如何,您都是通过实例引用调用它们的),它将按预期工作。

关于java - super 类的调用方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27382167/

10-11 05:04