泛型超类和超类类之间的区别 [英] Difference between generic super class and super class type

查看:259
本文介绍了泛型超类和超类类之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解下面两个代码片段之间的区别。有人可以帮我解释一下吗?



首先,我必须说我有很多类来扩展名为 BaseEntity ,那么以下代码片段的区别,优点和缺点是什么?

  // 1 
public< T扩展BaseEntity> T getName(T t){
return t;
}

// 2
public BaseEntity getName(BaseEntity t){
return t;


解决方案

第一个片段更加灵活因为它保留了 T 的实际类型。假设您有一个子类:

  class SubEntity extends BaseEntity {} 


$ b

在第一种情况下,您可以编写:

  SubEntity结果= getName(new SubEntity()); 

但在第二种情况下,您需要投射:

  SubEntity result =(SubEntity)getName(new SubEntity()); 


I can't understand the difference between the two code snippets below. Can someone help me with a simple explanation?

First of all, I have to say that I have a lot of classes that extend a super class named BaseEntity, so what are the differences, benefits and drawbacks of the following snippets?

// 1
public <T extends BaseEntity> T getName(T t) {
    return t;
}

// 2
public BaseEntity getName(BaseEntity t) {
    return t;
}

解决方案

The first snippet is more flexible as it preserves the actual type of T. Suppose you have a subclass:

class SubEntity extends BaseEntity {}

In the first case you can write:

SubEntity result = getName(new SubEntity());

But in the second case you will need a cast:

SubEntity result = (SubEntity)getName(new SubEntity());

这篇关于泛型超类和超类类之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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