Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T and inheritance in Java

Tags:

java

generics

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

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'm getting a null pointer exception when trying to manipulate with someString. So, the T.F is null, but T is B, so it should be "somestring"! Why?

like image 261
artem Avatar asked Jun 25 '26 09:06

artem


2 Answers

You can't Override fields. Since it is extends A, it will always use the field in A.

Add a getter in class A and B that returns F. From there, Override the method in A with the one in B.

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

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

This doesn't have to do with generics.

The fields of a class cannot be overridden by a subclass - only methods can. So, even if you define a field in your subclass with the same name as the one in the superclass, you're merely creating a new field that simply happens to have the same name but actually shadows (not overrides) the previous one.

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

like image 40
Theodoros Chatzigiannakis Avatar answered Jun 27 '26 21:06

Theodoros Chatzigiannakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!