3

我有两节课。Status1Status2

这两种状态有一个共同点:

protected A a;

和一个不常见的:

class Status1 {
    protected A a;
    protected ListStatus1.B version;
}

B在课堂static classStatus1

class Status2 {
    protected A a;
    protected Status2.C version;
}

C在课堂static classStatus2

所以现在我想创建界面Status

在这里我可以补充variable A。现在我需要添加getVersion应该返回静态类的方法Status1 / Status2

protected abstract ?? getVersion();

但我不知道return type应该有什么

我尝试添加到这个接口静态类和这个类返回但没有成功

4

4 回答 4

2

“正确的做法”是让两个静态类 B 和 C 实现一个共同的 empty interface,我们称之为“版本化”

public interface Versioned{}

static class B implements Versioned{
...
}
static class C implements Versioned{
...
}

之后,您可以编写:

 protected abstract Versioned getVersion();

并且您的方法将被允许返回 B 或 C。

于 2012-11-05T10:57:05.133 回答
1

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

于 2012-11-05T10:52:37.880 回答
1

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.

于 2012-11-05T10:54:30.737 回答
0

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();
于 2012-11-05T10:54:30.083 回答