简体   繁体   English

覆盖嵌套在Java中参数化外部类中的非参数化类

[英]Overriding non-parameterized classes nested in a parameterized outer class in Java

Can someone please help with the syntax of subclassing a non-parameterized nested class inside a parameterized outer class, like the following? 有人可以帮忙在参数化外部类中将非参数化嵌套类子类化的语法,如下所示吗?

public abstract class Foo<T> {

    public class Bar {
        Set<T> aSet;
    }

    abstract class Baz {
        abstract void doSomething(Map<? extends Bar, T> aMap);
    } 
}

Then in a separate file, I'm not entirely sure how to define the type variable S here without parameterizing ConcreteBaz . 然后,在一个单独的文件中,我不确定如何在不参数ConcreteBaz情况下定义类型变量S And I can't use a wildcard variable like extends Foo<?>.Baz (I think) because I need access to that generic type variable in the doSomething method: 而且我不能使用像extends Foo<?>.Baz这样的通配符变量,因为我需要在doSomething方法中访问该通用类型变量:

public class ConcreteBaz extends Foo<S>.Baz {    // compilation error

    public ConcreteBaz(Foo<S> foo) { foo.super(); }

    public void doSomething(Map<? extends Foo<S>.Bar, S> aMap) { ... }

}

Can someone please help me figure out a way around this? 有人可以帮我解决这个问题的方法吗? Thanks. 谢谢。

Your problem is that the nested class is nonstatic. 您的问题是嵌套类是非静态的。 I'll check it out, but I'm pretty sure you cannot subclass such classes, except maybe if nested in the same class, or when creating an anonymous type. 我会检查一下,但是我很确定您不能将此类归为子类,除非嵌套在同一类中,或者在创建匿名类型时除外。

Is declaring the nested class static viable? 声明嵌套类静态可行吗? Them it would definitely work. 他们肯定会工作。

Edit: scratch all that. 编辑:从头开始。 I don't have a compilation error. 我没有编译错误。 What is S in your case? 什么是S ,你的情况? You do realize you have to pass a concrete class to Foo, and cannot leave it parametrized with an unknown parameter S? 您是否意识到必须将具体类传递给Foo,并且不能让它使用未知参数S进行参数设置?

如果ConcreteBaz需要引用类型参数,则意味着它需要类型参数本身:

public class ConcreteBaz<S> extends Foo<S>.Baz {

Declare S as a type parameter: S声明为类型参数:

public class ConcreteBaz<S> extends Foo<S>.Baz {

Otherwise the compiler will think S is a concrete type instead of a type parameter. 否则,编译器会认为S是具体类型而不是类型参数。

Complete example: 完整的例子:

public class ConcreteBaz<S> extends Foo<S>.Baz {
    public ConcreteBaz(Foo<S> foo) {
        foo.super();
    }

    @Override
    void doSomething(Map<? extends Foo<S>.Bar, S> aMap) {
        // ...
    }
}

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

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