T and inheritance in Java

I have a class A with 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 with a method that uses the F field:

class C<T extends A> {
   public void someMethod() {
      String someString = T.F;
      // Manipulations with someString
   }
}

      

And then my code that calls it.

C<B> c = new C<B>();
c.someMethod();

      

and I am getting a null pointer exception when trying to manipulate with someString. So TF is null, but T is B, so it must be "somestring"! Why?

+3


source to share


4 answers


You cannot override fields. Since it expands A, it will always use the field in A.

Add a receiver to class A and B that returns F. From there, override the method in with the name in B.



class A {
    public String getF(){
        return null;
    }
}

class B {
    @Override
    public String getF(){
        return "someString";
    }
}

      

+7


source


It is not related to generics.

Class fields cannot be overridden by a subclass - only methods can be used. This way, even if you define a field in your subclass with the same name as your superclass, you are simply creating a new field that just has the same name, but is actually a shadow (rather than overriding) the previous one.



Consider assigning an assignment with a default value for the field in the constructor of your subclass. Then it should work.

+2


source


A static member in Java can be hidden, but not overridden. A static member reference is resolved at compile time - and at compile time the only known type of T is A.

See http://www.coderanch.com/how-to/java/OverridingVsHiding .

Edit: The field cannot be overridden anyway, whether it is static or instance.

+2


source


  • This is because all members static

    A

    are shared A

    and cannot be inherited B

    .

  • No new member static

    that is absent in A

    may be present in B

    .

  • Practically when you speak

    class C < T extends A > { ... }

You can only use methods (both static and instance - if @Override

n) and fields that are common in A

. So, since F

it is not an instance field, it is not overridden and the JVM detects the presence F

in A.

Hence, you get NPE.

+1


source







All Articles