Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static and overriding in Java


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.

like image 935
Abhishek Jain Avatar asked Dec 27 '25 16:12

Abhishek Jain


1 Answers

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 :-)

like image 102
Péter Török Avatar answered Dec 31 '25 14:12

Péter Török



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!