Reputation: 2353
I am attempting to make a parent class that has an object element within it, but I want to restrict this object to a type that extends the parent class. I have tried using generics in the form of
<T extends ParentClass> T
but this doesn't work.
Here is an example of what I am I currently working with.
public class ParentEvent {
private Object event;
private String type;
private Date time;
private String id;
public ParentEvent() {
event = null;
type = null;
time = null;
id = null;
}
public ParentEvent(String type, String id, Date time, Object event) {
this.event = event;
this.type = type;
this.time = time;
this.id = id;
}
public Object getEvent() { return event; }
public void setEvent(Object event) { this.event = event; }
// Other get/set methods removed for clarity
}
How would I go about restricting the Object referenced in the above code to one that extends the parent class?
Upvotes: 0
Views: 90
Reputation: 5744
This doesn't need generics. private ParentEvent event;
should do exactly what you're after. You may also want to make ParentEvent abstract.
Upvotes: 0
Reputation: 9785
Do you mean this:
public class ParentEvent<T extends ParentEvent<?>>
{
private T event;
...
public T getEvent() {...}
...
public void setEvent(T event) { ... }
}
And then, the child is:
public class ChildEvent extends ParentEvent<ChildEvent>
Upvotes: 1