Java泛型扩展类参数 [英] Java Generics Extends Class Parameter

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

问题描述

我收到一个错误,并且在我的程序中有这个结构

  public interface Shapes< T> {
//这里的方法
}

public class ShapeAction< T>实现Shapes< T> {
//这里的方法和实现
}

public class Circle extends ShapeAction< T> {
//这里的一些方法
}

错误指向类Circle延伸Shapes< T 它说T无法解析为某种类型。如果我将T设置为字符串,错误将消失,但这也意味着我只能使用一种数据类型。我应该在<>内部放置什么,以便我可以使用任何数据类型(String,int,double等),或者我是否以错误的方式执行了这些操作?

解决方案

有两个不同的概念。当你写出

  public class ShapeAction< T> 

这意味着您正在创建一个类,该类在实例化时将用某个类进行参数化。你不知道它会是什么时候,所以你把它称为 T



但是,当你写出

  public class Circle extends ShapeAction< T> 

这意味着您希望 Circle 成为用 T 参数化的 ShapeAction 的子类。但是什么是 T ?编译器无法说明:您在没有任何类型变量的情况下声明 Circle



您有两种选择。您也可以创建Circle类型:

  public class Circle< T>扩展ShapeAction< T> 

这样,当您创建 Circle 子类通用?使用 Object

  public class Circle extends ShapeAction< Object> 

通过这种方式 Circle 保持非泛型,但是您可以在超类中使用任何数据类型。


I received an error and I have this structure in my program

public interface Shapes<T>{
//methods here
}

public class ShapeAction<T> implements Shapes<T>{
//Methods and implementations here
}

public class Circle extends ShapeAction<T>{
//Some methods here
}

The error is pointing at class Circle extends Shapes<T> where it says "T cannot be resolved to a type". If I set T to string the error will go away but that also means I can only use one datatype. What should I put inside the <> so that I can use any datatype (String, int, double etc) or did I do this the wrong way?

解决方案

There are two different concepts. When you write

public class ShapeAction<T>

this means that you are creating a class which, when instantiated, will be parametrized with some class. You don't know at the time which it will be, so you refer to it just as T.

But when you write

public class Circle extends ShapeAction<T>

this means that you want Circle to be a subclass of ShapeAction parametrized with type T. But what is T? Compiler can't tell that: you declared Circle without any type variables.

You have two options. You can make Circle generic too:

public class Circle<T> extends ShapeAction<T>

This way when you make a new instance of Circle you specify what type it works with, and this extends to the superclass.

And what if you want to specify that ShapeAction can be of any type, but without making the subclass generic? Use Object:

public class Circle extends ShapeAction<Object>

This way Circle stays non-generic, but you can use any data types with the superclass.

这篇关于Java泛型扩展类参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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