简体   繁体   English

Java泛型类中的超类

[英]superclasses in generic classes in java

This is my first time here, but I do my best to describe my problem: 这是我第一次来这里,但我会尽力描述我的问题:

I have an abstract class A . 我有一个抽象类A I also have abstract classes B and C extending A . 我也有抽象类BC扩展了A Then I have classes extending B or C . 然后我有扩展BC类。

Now I have a generic class only accepting classes extending A . 现在我有一个通用类,只接受扩展A类。 ( class XYZ<ABC extends A>… ) class XYZ<ABC extends A>…

Now I basically want to create a method that works with the generic class, but only with instances that use a class extending B . 现在,我基本上想创建一个适用于泛型类的方法,但仅适用于使用扩展了B的类的实例。

I tried something like this: 我尝试过这样的事情:

public void method(XYZ<B> t){}

This sadly didn't work. 可悲的是这没有用。 The IDE wanted me to have either the type of t or the other way around. IDE希望我拥有t的类型或其他类型。

Now the questions: 现在的问题:
Why does this not work? 为什么这不起作用? It seems that it wouldn't cause any problems, because a subclass has to provide all methods from the superclass. 看起来不会造成任何问题,因为子类必须提供超类的所有方法。
Is there a way around this except of making a method for every single subclass of B or changing the type of the object i want to use? 除了为B的每个子类创建方法或更改我要使用的对象的类型之外,是否有其他方法可以解决?

example code: 示例代码:

public class main {

public static void main(String[] args) {
    ArrayList<Abc> foo = new ArrayList<>();
    xyz(foo);
}
private void xyz(ArrayList<B> abs){}


private static abstract class  A{}
private static abstract class  B extends A{}
private static abstract class  C extends A{}
private static class Abc extends B{}
}

Try it like this: 像这样尝试:

public class Main {

    public static void main(String[] args) {
        ArrayList<Abc> foo = new ArrayList<>();
        xyz(foo);
    }

    private static <T extends B> void xyz(ArrayList<T> abs){
        System.out.print("running xyz");
    }


    private static abstract class  A{}
    private static abstract class  B extends A{}
    private static abstract class  C extends A{}
    private static class Abc extends B{}
}

Seems to be what you are aiming for. 似乎是您的目标。 Take a look here for more information. 在这里查看更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM