如何将泛型类型限制为 Java 中的特定类型? [英] How do I restrict a generic type to specific types in java?

查看:36
本文介绍了如何将泛型类型限制为 Java 中的特定类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有通用变量的类.我想将该变量限制为一个集合类型(如汽车、自行车等)如下所示:

I have a class with a generic variable. I want to restrict that variable to a set of types (like Car, Bike, ...) as shown below:

class Garage{
   Class<K> ownerStaff;

   public Garage(Car c){
      this.ownerStaff = c;
   }
   public Garage(Bike b){
      this.ownerStaff = b;
   }
   ...
}

所以genericVariable"只能是汽车、自行车或我想要的任何其他类型,但不能是任何东西.我怎么能做这样的事情?

So the "genericVariable" can be only a Car, a Bike or any other type I want but not anything. How can I do something like that?

注意:我想我可以制作一个父类Vehicle",然后这样写(如果我错了,请纠正我)

Note: I think I can make a parent class "Vehicle" and then write it that way (correct me if I'm wrong)

class Garage<K extends Vehicle>{
   Class<K> ownerStaff;

   public Garage(Class<K> c){
      this.ownerStaff = c;
   }
}

但我不想要父类并使我的所有类都扩展Vehicle"并且我可能不想输入例如Garage 当我实例化一个车库"时.

but I don't want a parent class and make all my classes extends "Vehicle" and may I don't want to type e.g. Garage<Car> when I instantiate a "Garage".

谢谢

推荐答案

你的对象最终必须有某种共同的行为,否则将它们放在同一个 Garage.因此,正如@perelman 建议的那样,只需在接口中声明这种常见行为并使用它(无泛型):

You're objects eventually have to have some sort of common behavior, or else it wouldn't make sense to place them in the same Garage. So as @perelman suggested, simply declare this common behavior in an interface and use that (no generics):

public interface Vehicle {
    // common behavior declared, if any
}

public class Car implements Vehicle {
    // Implementation
}

public class Bike implements Vehicle {
    // Implementation
}

public class Garage {
    Vehicle vehicle;

    public Garage(Vehicle v) {
       vehicle = v;
    }
}

这篇关于如何将泛型类型限制为 Java 中的特定类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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