Agenericclassthatletsmehavedifferentreturntypes(Java)

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

回答

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.


以上是Agenericclassthatletsmehavedifferentreturntypes(Java)的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>