Java – inheritance in static methods
•
Java
Why does the following code print "master"?
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 points to an instance of submain, so it should conceptually print "submain"
Solution
Static methods are resolved on variables of compile - time type M is the main type, so the method in main is called
If you change it to submain M..., the method on submain will be called
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码