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

标签 java generics inheritance multiple-inheritance

我这里有一个框架,它使用一个对象来维护其他对象与其交互时的状态。我希望与状态交互的对象(“操作”)通常可以接受状态对象将实现的接口(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/

相关文章:

java - 如何使用循环填充 FXCollections.observableArrayList? [javafx]

c# - IList<T>.Split() 扩展方法的方法签名

c# - 无法将 List<int[*]> 转换为用反射实例化的 List<int[]>

java - JMS QueueBrowser 卡在 getEnumeration() 上

java - 在Android中为一组对象设置动画

java - Android studio在浏览SDK源代码时只找到 "some"类

c# - C# 泛型中的类特定函数 - 对 UWP 模板 Observable 进行轻微修改

c++ - C++:返回具有继承对象的基于范围的循环迭代器

c++打印出具有重载函数的对象数组

c++ - 在 C++ 中使用类层次结构时是否应该避免向下转型?