【问题标题】:How to use Class Objects with Inheritance如何使用具有继承的类对象
【发布时间】:2018-10-08 03:47:05
【问题描述】:

我有一个父类Parent,有两个子类AB。 A 有一个类Wrapper,其中包含一个接口Function,它允许程序员为每个包装器指定一个特定的方法。

Wrapper 包含变量Class<Parent> inputClassClass<Parent> outputClass,它们指定输入和输出类型。 Wrapper 应该将 A 映射到 A 或 B,或将 B 映射到 A 或 B。

当我尝试调用包装构造函数Wrapper(Class<Parent> input, Class<Parent> output, Function func) 时,出现了我的问题。 Eclipse 给我一个错误,因为我尝试将 A.classB.class 放入 inputoutput。鉴于 A 和 B 是 Parent 的子类,我认为它们可以传递给构造函数。我该如何实现?

public class Parent {
    protected int value;
    public void setValue(int x){ value = x; }
    public int getValue(){ return value; }
}


public class A extends Parent{
    public A(){ setValue(1); }
    public A(B b){ setValue( b.getValue()); }
}

public class B extends Parent{
    public B(){ setValue(2); }
    public B(A a){ setValue(a.getValue()); }
}


public class Wrapper{
    protected Class<? extends Parent> inputClass;
    protected Class<? extends Parent> outputClass;
    protected interface Function{
        public Parent of(Parent input);
    }
    protected Function function;
    public Wrapper(Class<? extends Parent> in, Class<? extends Parent> out, Function func) {
        inputClass = in;
        outputClass = out;
        function = func;
    }

    public Parent of(Parent input){
        try{
            Parent output = function.of( inputClass.getConstructor( input.getClass() ).newInstance(input) );
            return outputClass.getConstructor( output.getClass() ).newInstance( output );
        } catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

public class Main {
    public static void main(String[] args){
        ///Error occurs here. Can't take A.class in for Parent.class
        Wrapper wrapper = new Wrapper(A.class,B.class, new Function(){
            @Override
            public Parent of(Parent p) {
                return null;
            }
        });     
    }
}

【问题讨论】:

  • 我认为Class&lt;Parent&gt; in 应该更像Class&lt;? super Parent&gt; in,但我没有尝试过,所以你可能需要再捏造一点(你必须将它应用于两个参数)
  • 我认为您的 Wrapper 构造函数中需要 &lt;? extends Parent&gt; 以便允许子类。否则,您仅将 inout 限制为 Parent
  • @dave 我做了这些更改,但它仍然给我同样的错误。在发布之前我实际上已经尝试过了。
  • @user2303321 你能仔细检查一下吗?我将您的最新代码复制到 IntelliJ 中,它为我编译没有错误(使用 Java 8)。

标签: java class object inheritance


【解决方案1】:

问题不是来自A.classB.class,而是来自嵌套在Wrapper 类中的接口Function。我需要在main的构造函数中写new Wrapper.Function

【讨论】:

    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2021-07-25
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多