dane131
dane131

Reputation: 187

Java inheritance in DTOs

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.

Upvotes: 0

Views: 2627

Answers (3)

Timothy Truckle
Timothy Truckle

Reputation: 15622

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?

Upvotes: 0

lexicore
lexicore

Reputation: 43651

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;
}

Upvotes: 1

Leo Aso
Leo Aso

Reputation: 12463

You have generics. Use them.

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

class Aext extends A<Cext> {
}

Upvotes: 1

Related Questions