将非泛型类扩展为通用类 [英] Extending a non-generic class to a generic class

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

问题描述

包org.apache.commons.collections.buffer中的Java类CircularFifoBuffer是非通用的,可以存储任何类的对象。



创建一个只有T类对象的泛型版本。我的第一个想法是扩展CircularFifoBuffer并简单地写一个新的'add'方法:

  public class CircularFifoQueue< T> extends CircularFifoBuffer {

public boolean add(T data){
return super.add(data);
}

}

add'方法,允许添加任意类的对象。有没有办法使用继承而不是组合(所以我不必重新实现所有的CircularFifoBuffer的方法),但阻止类的用户添加非T对象?


public class CircularFifoQueue< T> {
private CircularFifoBuffer buffer = new CircularFifoBuffer();

public boolean add(T data){
return buffer.add(data);
}

//实现所需的所有其他方法
}


b $ b

所以内部缓冲区接受一切,但是包装器确保只能添加​​ T 类型对象。问题:现在缓冲区没有实现任何接口。所以它的用法现在有点有限(如果你需要发送一个 Buffer 例如不能使用它)


The Java class CircularFifoBuffer in the package org.apache.commons.collections.buffer is non-generic, and can store objects of any class.

I would like to create a generified version of this, that can only hold objects of class T. My first thought was to extend CircularFifoBuffer and simply write a new 'add' method:

public class CircularFifoQueue<T> extends CircularFifoBuffer {

    public boolean add(T data) {
        return super.add(data);
    }    

}

However, this leaves the old 'add' method in place, allowing for objects of arbitrary class to be added. Is there a way around this that uses inheritance rather than composition (so that I don't have to re-implement all of CircularFifoBuffer's methods) but prevents users of the class from adding non-T objects?

解决方案

One idea is t implement your own buffer that just wraps the original one:

public class CircularFifoQueue<T> { 
  private CircularFifoBuffer buffer = new CircularFifoBuffer();

  public boolean add(T data) {
     return buffer.add(data);
  }    

  // implement all other methods that are needed
}

So the internal buffer takes everything but the wrapper makes sure that only T type objects can be added. Problem: right now the buffer does not implement any interface. So it's usage is a bit limited right now (you can't use it if you need to send a Buffer for example)

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

查看全文
相关文章
Java开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆