0

I have a class A with these properties:

class A {

String a;
String b;
.....
List<C> myList;
}

I want a class Aext that will extend A and will also "extend" myList properties,meaning:

class Aext extends A {

String x;
.....
List<Cext> myList;
....
}

where:

class Cext extends C {
 ......
}

But I cannot have a member in subclass with same name as superclass i.e : myList. Name must not be changed. I want an "extended" myList that has the properties of C plus the properties of Cext. A and B are DTOs so I want to sometimes return B as an "enriched" version of A without changing names,types etc.

dane131
  • 187
  • 5
  • 16

3 Answers3

1

You have generics. Use them.

class A<T extends C> {
String a;
String b;
.....
List<T> myList;
}

class Aext extends A<Cext> {
}
Leo Aso
  • 11,898
  • 3
  • 25
  • 46
1

Generics to the rescue.

class A<T extends C> {

protected String a;
protected String b;
.....
protected List<T> myList;
}

Now myList has elements of the type T which extends C.

When you subclass A with Aext you can specify Cext as the type of the elements for myList.

class Aext extends A<Cext> {

String x;
}
lexicore
  • 42,748
  • 17
  • 132
  • 221
0

In inheritance is discouraged for DTOs especially if you're going to instantiate objects from different stages in the inheritance hierarchy.

The reason is the relationship between equals() and hashcode().
how do I correctly override equals for inheritance in java?

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51