views:

72

answers:

3

public class B {

    static int i =1;

    public static int multiply(int a,int b)
    {
        return i;
    }

    public int multiply1(int a,int b)
    {
        return i;
    }

    public static void main(String args[])
    {
        B b = new A();
        System.out.println(b.multiply(5,2));
        System.out.println(b.multiply1(5,2));
    }
}

class A extends B
{
    static int i =8;

    public static int multiply(int a,int b)
    {
        return 5*i;
    }

    public int multiply1(int a,int b)
    {
        return 5*i;
    }

}

Output:

1

40

Why is it so? Please explain.

+5  A: 

You can not override static methods - they are statically bound to the class they are defined in. Thus, unlike instance methods, they are not polymorphic at all.

In fact, b.multiply(5,2) should result in a compiler warning, saying that static method calls should be scoped with the class rather than an instance, hence the correct form would be B.multiply(5,2) (or A.multiply(5,2)). This then clarifies which method is actually called.

If you omit the compiler warning, you easily get confused :-)

Péter Török
+2  A: 

Calling static methods via references is a really bad idea - it makes the code confusing.

These lines:

B b = new A();
System.out.println(b.multiply(5,2));
System.out.println(b.multiply1(5,2));

are compiled into this:

B b = new A();
System.out.println(B.multiply(5,2));
System.out.println(B.multiply1(5,2));

Note that the calls don't rely on b at all. In fact, b could be null. The binding is performed based on the compile-time type of b, ignoring its value at execution time.

Polymorphism simply doesn't happen with static methods.

Jon Skeet
Small oversight; multiply1() is not static so it's compiled into `b.multiply1(5,2)` which explains the 40 (from A) and 1 (from B).
rsp
Thanks for your clarification.please correct your answer. multiply1 is not a static method.
Abhishek Jain
A: 

Because b is of type B. If you use eclipse you will notice a warning which indicates as much.

The static method multiply(int, int) from the type B should be accessed in a static way

Tim Bender