简体   繁体   中英

how to declare such a java class?

the following java class declaration is incorrect:

public class BookKeeping<T extends Transaction<K extends Money>> { ... }

here, one cannot use the generic declaration K extends Money .

my question is why this declaration is not allowed? And how should one declare such a class with java generics?

solution

class Money {

}

class Dollar extends Money {

}

class Transaction<T extends Money> {

}

public class BookKeeping<K extends Money,T extends Transaction<K>> {
    public void foo () {
        Dollar d = new Dollar();
        Transaction<Dollar> t = new Transaction<Dollar>();
        BookKeeping<Dollar, Transaction<Dollar>> b = new BookKeeping<Dollar, Transaction<Dollar>>(); 
    }
}

您需要指定通用参数和相应的约束,然后将它们用于任何其他参数。

public class BookKeeping<K extends Money, T extends Transaction<K>> { ... }

public class BookKeeping<K ,T extends Transaction<K extends Money>> { ... }

You need to "declare" the K generic before you can nested or use it. Its the same rule as local variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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