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.
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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With