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

}

Conclusion:

1

40

Why is that? Explain, please.

+3
source share
3 answers

Calling static methods via links is a really bad idea - this makes the code confusing.

These lines are:

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

compiled into this:

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

Note that calls do not rely on at all b. In fact, it bcan be zero. Binding is performed based on the type of compilation time b, ignoring its value at runtime.

Polymorphism simply does not happen with static methods.

+2
source

static - , . , .

, b.multiply(5,2) , , static , , b.multiply(5,2) ( A.multiply(5,2)). , .

, : -)

+5

b B. eclipse, , , .

multiply (int, int) B

0

Source: https://habr.com/ru/post/1750457/


All Articles