3

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);
    }
}
Decayer4ever
  • 73
  • 1
  • 8
  • 3
    Polymorphism works only for methods which are not `final` or `private` or `static`. – Pshemo Jan 23 '15 at 20:46
  • Also, if you want the `aMethod()` in `SomethingElse` to override the `aMethod()` in `Something` then you should give it the `@Override` attribute, though you would also have to remove the `static` – Al Lelopath Jan 23 '15 at 20:47

3 Answers3

8

Because polymorphism only applies to instance methods.

The static method aMethod invoked here

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

refers to the aMethod declared in Something.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
1

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.

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
0

Because int x is declared in the class Something. When you make the SomethingElse object, you first make a Something object (which has to set x, and it uses the aMethod() from Something instead of SomethingElse (Because you are creating a Something)). This is because aMethod() is static, and polymorphism doesn't work for static methods. Then, when you print the x from m, you print 20 since you never changed the value of x.

Aify
  • 3,543
  • 3
  • 24
  • 43