Java – overriding protected methods of superclasses
•
Java
In the following example, why does string B print null and string c print "GG"
If I am wrong, please correct me whenever the subclass (bclass) overrides the protected method (i.e. initclass()) of the superclass (aclass) If you instantiate a subclass A superclass must use the override method specified by its subclass
public class Example { public class AClass { private String a; public AClass() { initClass(); } protected void initClass() { a = "randomtext"; } } public class BClass extends AClass { private String b = null; private String c; @Override protected void initClass() { b = "omg!"; c = "gg"; } public void bValue() { System.out.println(b); // prints null System.out.println(c); // prints "gg" } } public static void main(String[] args) { Example.BClass b = new Example().new BClass(); b.bValue(); } }
Solution
As of JSF 12.5
In the example, you can see the execution order The first step is to call the constructor to the object constructor This happens later:
Since your instance variable B is initialized to null, it will be null again later
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
二维码