Why does the below code print “Main”?
public class Main
{
public static void method()
{
System.out.println("Main");
}
public static void main(String[] args)
{
Main m = new SubMain();
m.method();
}
}
class SubMain extends Main
{
public static void method()
{
System.out.println("SubMain");
}
}
At runtime, m is pointing to an instance of Submain, so it should conceptually print “SubMain”.
Static methods are resolved on the compile-time type of the variable.
mis of typeMain, so the method inMainis called.If you change it to
SubMain m ..., then the method onSubMainwill be called.