1

This program is supposed to individually call the funFact of each subclass but instead, it calls the funFact method only from the Mammal class. What am I doing wrong?

 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
Eran
  • 387,369
  • 54
  • 702
  • 768
Fluffle
  • 181
  • 1
  • 7

2 Answers2

6

funFact is static. Overriding doesn't work on static methods.

Remove the static keyword from all your methods (as you are calling them via an instance reference anyway) and it will work as you expected.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

If you "override" the static method, you are hiding the method, not really overriding.

read this:

https://docs.oracle.com/javase/tutorial/java/IandI/override.html

the "Static Methods" section exactly answers your question.

Kent
  • 189,393
  • 32
  • 233
  • 301