Decayer4ever
Decayer4ever

Reputation: 73

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);
    }
}

Upvotes: 3

Views: 913

Answers (3)

MaxZoom
MaxZoom

Reputation: 7763

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.

Upvotes: 1

Aify
Aify

Reputation: 3537

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.

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280179

Because polymorphism only applies to instance methods.

The static method aMethod invoked here

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

refers to the aMethod declared in Something.

Upvotes: 8

Related Questions