扩展通用类 [英] Extending Generic Classes

查看:117
本文介绍了扩展通用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 type Extend1 has two (unbounded) type arguments T and E. This tells the Java compiler that those who use Extend1 need to specify the types.
  • in extends MyGeneric<T,E> you use the previously defined type arguments. If T and E were not known to be type arguments here, then T and E would be simple type references, i.e. the compiler would look for classes (or interfaces, ...) named T and E (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆