Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static methods and polymorphism

I have a simple question that I just can't figure out a good answer for. Why does the following Java program display 20? I would prefer a detailed response if possible please.

class Something{
    public int x;
    public Something(){
        x=aMethod();
    }
    public static int aMethod(){
        return 20;
    }
}
class SomethingElse extends Something{
    public static int aMethod(){
        return 40;
    }
    public static void main(String[] args){
        SomethingElse m;
        m=new SomethingElse();
        System.out.println(m.x);
    }
}
like image 815
Decayer4ever Avatar asked Sep 11 '26 06:09

Decayer4ever


2 Answers

Because polymorphism only applies to instance methods.

The static method aMethod invoked here

public Something(){
    x=aMethod();
}

refers to the aMethod declared in Something.

like image 58
Sotirios Delimanolis Avatar answered Sep 12 '26 20:09

Sotirios Delimanolis


The inheritance for static methods works differently then non-static one. In particular the superclass static method are NOT overridden by the subclass. The result of the static method call depends on the object class it is invoke on. Variable x is created during the Something object creation, and therefore that class (Something) static method is called to determine its value.

Consider following code:

public static void main(String[] args){
  SomethingElse se = new SomethingElse();
  Something     sg = se;
  System.out.println(se.aMethod());
  System.out.println(sg.aMethod());
}

It will correctly print the 40, 20 as each object class invokes its own static method. Java documentation describes this behavior in the hiding static methods part.

like image 26
MaxZoom Avatar answered Sep 12 '26 19:09

MaxZoom