Inheritance in T and Java
•
Java
I have a class a static field F:
class A { public static String F = null; }
Class B:
class B extends A { public static String F = "somestring"; }
And a typed class using the method of field F:
class C<T extends A> { public void someMethod() { String someString = T.F; // Manipulations with someString } }
Then my code calls it
C<B> c = new C<B>(); c.someMethod();
When I try to operate with somestring, I get a null pointer exception Therefore, T. f is empty, but t is B, so it should be "somestring"! Why?
Solution
You cannot overwrite fields Since it is extension a, it will always use the fields in a
Add a getter that returns f in class A and class B From there, overwrite the method in a with the method in a
class A { public String getF(){ return null; } } class B { @Override public String getF(){ return "someString"; } }
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
二维码