I have two classes. Status1
and Status2
these two status has one variable common:
protected A a;
and one which isnt common:
class Status1 {
protected A a;
protected ListStatus1.B version;
}
B
is static class
inside of Status1
class
class Status2 {
protected A a;
protected Status2.C version;
}
C
is static class
inside of Status2
class
so now I want to create interface Status
here I can add variable A
. Now I need to add method getVersion
which should return static class inside of Status1 / Status2
protected abstract ?? getVersion();
but I dont know what return type
should be there
I try to add to this interface static class and this class return but with no succes
The "right way" is to let the two static classes B and C implement a common empty interface
, let's call is "Versioned"
public interface Versioned{}
static class B implements Versioned{
...
}
static class C implements Versioned{
...
}
After that, you can write:
protected abstract Versioned getVersion();
and your method will be allowed to return either B or C.
I think Object
should do the trick!
however, while accessing any fields of the object you might face problems. Thus, I suggest you to have an interface Version
which is implemented by the inner classes of both the statuses.
Hope this helps,
Cheers
If the difference between Status1.B
and Status2.C
is essential for your object model, you can make Status
generic:
public interface Status<V> {
public V getVersion();
}
public class Status1 implements Status<Status1.B> {
public Status1.B getVersion() { ... }
...
}
Otherwise you can introduce an interface for both version classes, as suggested by other answers.
One way is to create an interface (let's call it IVersion
) and make both version classes implement that interface. The getVersion()
method can then return this interface:
protected abstract IVersion getVersion();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.