-2

Trying to work on an example from a book on method overriding. The code has two classes Veggies and Pumpkin.The only confusion i have is if the object of pumpkin is assigned to the myveggie object, why does it call the method of veggies class since the object is from derived class. I am sure this has something to do with static method,but I could get a more clear idea.

 class Veggies {
        public static void staticMethod(){
            System.out.println("Veggies static method");
        }
    public void instancemethod(){
        System.out.println("Veggies instance method");
    }
}
public class Pumpkin extends Veggies{
        public static void staticMethod(){
            System.out.println("Pumpkin static method");
        }
        @Override
        public void instancemethod(){
            System.out.println("Pumpkin instance method");
        }
        public static void main(String[] args) {
            Pumpkin myPumpkin=new Pumpkin();
            Veggies myveggie=myPumpkin;
            myveggie.staticMethod();
            myveggie.instancemethod();

        }
    }
Bissi singh
  • 50
  • 1
  • 11

1 Answers1

2

As this question:

explains, static methods cannot be overridden in Java.

What you have in your example, is code that is calling a static method via an instance. This is bad practice.

What actually happens is that the static type of the variable (not the reference!) is resolved at compile time to a class. In this case, the class is Veggies. Then the compiler inserts a call to the static method of that class; i.e. Veggies.staticMethod().

Which is confusing ... because it looks like you should be dispatching to a static method associated with the reference. But that is not how Java works.

That's why this is bad practice, and why a lot of IDEs will warn you about it.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216