Generics question

M

Malcolm Ryan

I have a question about generics.

Say I have an interface:

interface Copyable<T> {
T copy();
}

and a pair of classes:

class Parent implements Copyable<Parent> {

Parent copy() {
....
}
}

class Child extends Parent {

Child copy() {
....
}
}

Because of type erasure, I can't indicate that Child implements
Copyable<Child> as well as Copyable<Parent>. Which is a problem because
I have another class which expects its type parameter to be Copyable:
and a class which expects Copyable things:

class Processor<T extends Copyable<T>> {
T process(T thing) {
T copy = thing.copy();
// .. do stuff with copy
return copy;
}
}

Now I can make a Processor<Parent> but not a Processor<Child>, which is
frustrating if I want to specify that some subclass of Processor only
works on Child. Is there any way to get around this?

Malcolm
 
T

Thomas Hawtin

Malcolm said:
interface Copyable<T> {
T copy();
}
class Parent implements Copyable<Parent> {
Parent copy() {
class Child extends Parent {
Child copy() {
Because of type erasure, I can't indicate that Child implements
Copyable<Child> as well as Copyable<Parent>. Which is a problem because

In general it's best to keep non-leaf classes abstract. So you get:

abstract class AbstractNode<THIS>
implements Copyable<THIS extends Parent<THIS>>

class Parent extends AbstractNode<Parent>

class Child extends AbstractNode<Child>

Quite often it's more convenient not to distinguish between elements of
a tree that may be leaves and those that may not.

For instance, Swing has JComponent whereas AWT splits Component and
Container. java.awt.Choice (a combobox) is not a Container, but
JComboBox must be a container for the Basic PL&F to work.

AWT uses a class hierarchy the opposite way round from that of the
classes above. Neither approach is wrong, but neither are correct either.

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

generics puzzle 57
Generics 12
Hairy generics question 29
[C#] Extend main interface on child level 0
Simple Javascript Inheritance Problem 0
Generics question 6
Tree design with generics 2
Generics annoyance 18

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top