扩展通用类 [英] Extending Generic Classes
问题描述
public class MyGeneric<T, E> {}
public class Extend1<T, E> extends MyGeneric<T, E> {}
public class Extend2 extends MyGeneric<String, Object> {}
据我所知,上述例子中的两个子类都是有效的。我想知道当子类实例化时,以及当它们是实际的类名时(即,它怎么知道T,E不是类名),在超类中给定的类型何时被Java定义?
As far as I am aware, both of the subclasses in the above example are valid. I was wondering how Java knows when the types given in the superclass are going to be defined when the subclass is instantiated, and when they are actual class names (i.e. How does it know T, E are not class names)?
旁注,是否允许(即使不常见)对通用类型使用多个字母?如果(通过一些计划的错误)如果类型与现有的类冲突如
A side note, is it permissible (even if uncommon) to use more than one letter for the generic types? What if (through some sever error of planning) The types conflict with an existing class e.g.
public class E{}
public class Foo<E>{}
会发生什么?
编辑:感谢您如此迅速回答。
要回答我的第一个问题, Joachim的回答是最有效的。
Thanks for answering so promptly. To answer my first question, Joachim's answer is most effective.
要回答这一问题, aioobe的答案更清楚
推荐答案
让我们来看看这个定义:
Let's look at this definition:
public class Extend1<T, E> extends MyGeneric<T, E> {}
这里 T
和 E
每次出现两次,在两个不同的角色
Here T
and E
are each present twice and in two different roles
- 在
Extend1< ; T,E>
您定义类型参数。这意味着类型Extend1
有两个(无界)类型参数T
和E
。 告诉Java编译器
Extend1
需要指定类型。 - 在
中扩展MyGeneric< T,E>
您可以使用先前定义的类型参数。如果T
和E
在这里不是类型参数,则T
和E
将是简单的类型引用,即编译器将寻找名为T
和
E
(很可能找不到它们)。
- in
Extend1<T,E>
you define type arguments. This means that the typeExtend1
has two (unbounded) type argumentsT
andE
. This tells the Java compiler that those who useExtend1
need to specify the types. - in
extends MyGeneric<T,E>
you use the previously defined type arguments. IfT
andE
were not known to be type arguments here, thenT
andE
would be simple type references, i.e. the compiler would look for classes (or interfaces, ...) namedT
andE
(and most likely not find them).
是的,类型参数遵循与Java中任何其他标识符相同的语法规则,因此您可以使用多个字母 ABC
或甚至可能令人困惑的名称 String
是合法的,但高度令人困惑。)
Yes, type arguments follow the same syntactic rules as any other identifier in Java, so you can use multiple letters ABC
or even names that can be confusing (using a type argument called String
is legal, but highly confusing).
单字母类型参数名称只是一个非常常见的命名策略。
Single-letter type argument names are simply a very common naming strategy.
这篇关于扩展通用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!