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.
Calling static methods via references is a really bad idea – it makes the code confusing.
These lines:
are compiled into this:
Note that the calls don’t rely on
bat all. In fact,bcould be null. The binding is performed based on the compile-time type ofb, ignoring its value at execution time.Polymorphism simply doesn’t happen with static methods.