Reputation: 43
Today I've been working with generic/parametric types in java () exercising my polymorphism understanding but since quite some time now I've been having an issue where I would have a generic class with a single method that returns a value, the reason is because I want to be able to call a method and by context been able to have different return types
class dummy <E>{
E value;
public E getValue(){
return value;
}
class dummy1 extends dummy<E>{
int value;
public int getValue(){
return int;
}
class dummy2 extends dummy<E>{
boolean value;
public boolean getValue(){
return boolean;
}
Is this possible? I'm not really sure if even this is the correct way of doing this kind of thing
Upvotes: 2
Views: 61
Reputation: 147164
The problem you have is that in Java primitives, such as int
and boolean
, cannot be generic arguments.
You need to swap these for equivalent reference types: Integer
and Boolean
.
Also E
is scoped to the dummy
class. You will need to provide the type argument to the superclass.
class Dummy<E> {
private E value;
public Dummy(E value) {
this.value = value;
}
public E getValue() {
return value;
}
}
class Dummy1 extends Dummy<Integer> {
public Dummy1(Integer value) {
this.value = value;
}
}
class Dummy2 extends Dummy<E> {
public Dummy2(Boolean value) {
this.value = value;
}
}
Or:
abstract class Dummy<E> {
public abstract E getValue();
}
class ReferenceDummy<E> extends Dummy<E> {
private final E value;
public Dummy1(E value) {
this.value = value;
}
@Override public E getValue() {
return value;
}
}
class Dummy1 extends Dummy<Integer> {
private int value;
public Dummy1(int value) {
this.value = value;
}
@Override public Integer getValue() {
return value;
}
}
class Dummy2 extends Dummy<Boolean> {
private boolean value;
public Dummy1(boolean value) {
this.value = value;
}
@Override public Boolean getValue() {
return value;
}
}
Note that, say, boolean getValue()
cannot override Boolean getValue()
for some reason.
Upvotes: 5