Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherited field in derived class - both solutions appear lame

I have some class X with the field A in it. It is a final field, initialized in constructor. Now I have a derived class Y where this field must always be an instance of B, a class that is derived from A. The problem, the class Y needs to call a number specific methods that are only available on the class B but not on its ancestor, A.

I see several solutions:

  1. Reuse the field of the type A, inherited from X, and inside the class Y, cast A to B. This makes my code full of nasty type casts.
  2. Add another field of the type B. Now there are no typecasts but we have two fields of slightly different type that must always hold the same value - also does not feel good.
  3. Add all methods that B provides also to A, throw NotImplementedException. This adds some strange methods that knowingly make no sense in that class.

Which is the most right way to deal with this field? Or maybe some other, better exists? I do not think this is very language specific but must be doable in Java I am using.

like image 331
Audrius Meškauskas Avatar asked Dec 20 '25 02:12

Audrius Meškauskas


1 Answers

The X type should probably be a generic type:

public class X<T extends A> {

    protected T a;

    public X(T a) {
        this.a = a;
    }
}

public clas Y extends X<B> {

    public Y(B b) {
        super(b);
    }

    public void foo() {
        // here, this.a is of type B, without any type cast.
    }
}
like image 110
JB Nizet Avatar answered Dec 21 '25 18:12

JB Nizet