开发者

Java: Subclassing a genericised class

开发者 https://www.devze.com 2022-12-18 11:39 出处:网络
I have a genericised class that I wish to subclass as follows: public class SomeTable<T extends BaseTableEntry>

I have a genericised class that I wish to subclass as follows:

public class SomeTable<T extends BaseTableEntry>
    extends BaseTable<T>
{

    public SomeTable(int rows, int cols)
    {
        s开发者_高级运维uper(rows, cols, SomeTableEntry.class);
        //Does not compile:
        //Cannot find symbol: constructor BaseTable(int, int, java.lang.Class<blah.blah.SomeTableEntry.class>)
    }
}

... where the genericised superclass is:

public class BaseTable<T extends BaseTableEntry>
{

    public BaseTable(int rows, int cols, Class<T> clasz)
    {
        ...
    }
...
}

I understand the compiler error, but cannot seem to find a workaround, other than to include an extra parameter in the SomeTable constructor.

Any suggestions?

Thanks!


This compiles:

public class SomeTable extends BaseTable<SomeTableEntry> {
    public SomeTable(int rows, int cols)
    {
        super(rows, cols, SomeTableEntry.class);
    }
}

It works with a cast:

public class SomeTable<T extends BaseTableEntry> extends BaseTable<T> {
    public SomeTable(int rows, int cols)
    {
        super(rows, cols, (Class<T>)SomeTableEntry.class);
    }
}

but I'm looking forward to someone posting the explanation for why the compiler requires the cast for the class.


It is possible to define the SomeTable constructor generically if you pass Class to it the same way as you do with the base class:

public class BaseTable<T extends BaseTableEntry>
{
    public BaseTable(int rows, int cols, Class<? extends T> clazz)
    {
        // ...
    }
}

class SomeTable<T extends BaseTableEntry>
extends BaseTable<T>
{
    public SomeTable(int rows, int cols, Class<? extends T> clazz)
    {
        super(rows, cols, clazz);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消