gpt4 book ai didi

java - 接口(interface)是否被视为实现它的类的父级?

转载 作者:行者123 更新时间:2023-12-02 13:47:39 25 4
gpt4 key购买 nike

我这里有一个框架,它使用一个对象来维护其他对象与其交互时的状态。我希望与状态交互的对象(“操作”)通常可以接受状态对象将实现的接口(interface)类型,但我在实现这项工作时遇到了困难。

我想根据特定的状态实现(或接口(interface))来定义框架对象本身,并且能够向其添加操作,只要它们直接或通过状态所定义的接口(interface)接受定义的状态即可实现。

据我了解,<? super S>定义意味着“某种类型是 S 的父类”,但我不确定 S 实现的接口(interface)是否符合此描述,因为它不完全是父类。

这是一个示例(不完全是编译代码):

Class Framework<State> {
addAction(Action<? super State> a) {} // adds to a list of actions to be run

run(State s) {
for(Action<? super State> a : actions) {
a.perform(s);
}
}
}

Interface IState1 {}

Interface IState2 {}

Interface Action<State> {
public void perform(State s);
}

Class Action1 implements Action<IState1> {}

Class Action2 implements Action<IState2> {}

Class CombinedState implements IState1, IState2 {}

public static void run() {
Framework<CombinedState> f = new Framework<CombinedState>();

// add is expecting Action<? super CombinedState> but getting Action<IState1>
f.add(new Action1()); // This doesn't seem to work
f.add(new Action2());

f.run(new CombinedState());
}

就泛型而言,接口(interface)算作父类吗?有没有什么方法可以不需要反射来实现这个?

最佳答案

import java.util.ArrayList;

class State{}

class Framework<State>
{
public ArrayList< Action< ? super State > >actions = new ArrayList< Action< ?super State > >();

void add(Action<? super State> a) {

actions.add(a);

}

void doRun(State s) {
for(Action<? super State> a : actions) {
a.perform(s);
}
}
}

interface IState1 {}

interface IState2 {}

interface Action<State> {
public void perform(State s);
}

class Action1 implements Action<IState1> {
public void perform( IState1 s )
{
System.out.println("Do something 1");
}
}

class Action2 implements Action<IState2> {

public void perform( IState2 s )
{
System.out.println("Do something 2");
}
}

class CombinedState implements IState1, IState2 {}

class Untitled {
public static void main(String[] args)
{
Framework<CombinedState> f = new Framework<CombinedState>();

// add is expecting Action<? super CombinedState> but getting Action<IState1>
f.add(new Action1()); // This doesn't seem to work
f.add(new Action2());

f.doRun(new CombinedState());
}
}

它在 OSX 上的 CodeRunner 中运行。

关于java - 接口(interface)是否被视为实现它的类的父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12149833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com