0

This is the code that I'm dealing with:

class Animal {

    public void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }

    public static void clank()
    {
        System.out.println("Clank in Animal");
    }
}

and

public class Cat extends Animal {

    public void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void clank()
    {
        System.out.println("Clank in Cat");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = new Cat();
        myAnimal.hide();
        myAnimal.override();
        myAnimal.clank();
    }
}

The output of this code is:

The hide method in Cat.
The override method in Cat.
Clank in Animal

why does declaring both clank methods as static doesn't allow the clank in Animal to be overridden? should the output be "Clank in Cat"? Thanks!

Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42
  • You should tag the language, but in this case, it doesn't matter. Same reason for most of them: https://stackoverflow.com/questions/2223386/why-doesnt-java-allow-overriding-of-static-methods – zzxyz Feb 13 '18 at 22:10

1 Answers1

0

Static methods are class methods, they don't need any instance to be called. Access to them is always resolved during compile time. So in this case, since the compile time type of myAnimal is Animal, calling myAnimal.clank() is equal to Animal.clank(). But if you write Cat myAnimal = new Cat(); and then call myAnimal.clank(), you will get Clank in Cat.

Java documentation says that

Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class

Note: You can also refer to static methods with an object reference like instanceName.methodName(args) but this is discouraged because it does not make it clear that they are class methods.

Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42