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.

Abhishek Jain
  • 6,296
  • 7
  • 26
  • 34
  • 1
    See http://stackoverflow.com/questions/2223386/why-doesnt-java-allow-overriding-of-static-methods – ewernli Jun 17 '10 at 10:01

3 Answers3

5

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
  • 114,404
  • 31
  • 268
  • 329
2

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 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 Jun 17 '10 at 09:43
  • Thanks for your clarification. please correct your answer. multiply1 is not a static method. – Abhishek Jain Jun 17 '10 at 09:43
0

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
  • 20,112
  • 2
  • 49
  • 58