创建通用接口限于自己的类 [英] Create generic Interface restricted to own class

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

问题描述

我想为这两个类创建一个通用接口,但我不确定如何正确指定泛型。

c $ c> public class ThingA实现Thing {
public ThingA createCopy(ThingA original);
}

公共类ThingB实现Thing {
public ThingB createCopy(ThingB original);
}

我试过了。

  public interface Thing< V extends Thing< V>> {
public V createCopy(V original);

}

但是我仍然可以做这样的事情,这不应该被允许。

  public class ThingB implements Thing< ThingA> {
public ThingA createCopy(ThingA original);


解决方案

$ c $>这个关键字泛型(也不适用于方法参数和返回值声明),因此你不能完全按照你想要的来做。

换句话说,接口将允许确保类中的所有方法使用一致的类型,但不能引用类类型本身。


I would like to create a generic interface for those two classes but I'm not sure how to specify the generics the right way.

public class ThingA implements Thing {
    public ThingA createCopy(ThingA original);
}

public class ThingB implements Thing {
    public ThingB createCopy(ThingB original);
}

I tried it this.

public interface Thing<V extends Thing<V>> {
    public V createCopy(V original);

}

But I'm still able to do things like this, which shouldn't be allowed.

public class ThingB implements Thing<ThingA> {
    public ThingA createCopy(ThingA original);
}

解决方案

There is no this key-word generics (nor for methods parameters and return values declaration) and thus you cannot do exactly what you want.

In other words the interface will permit to ensure all the methods in the class use consistent types, but not to reference the class type itself.

这篇关于创建通用接口限于自己的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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