tj-recess
tj-recess

Reputation: 1809

How to extend a generic class with added constraints in java?

I want to extend my BinaryTree class so that only Integer parameters are accepted and I can reuse the code.

public class BinaryTree<T extends Comparable<T>>  
{/*code omitted for convenience*/}  
public class BinaryTreeInt<T extends Integer> extends BinaryTree<T>  
{/*code omitted for convenience*/}

I get following error on compilation-

BinaryTreeInt.java:1: type parameter T is not within its bound
public class BinaryTreeInt<T extends Integer> extends BinaryTree<T>
                                                                 ^
1 error

Can someone guide how to write code for such inheritance?

Upvotes: 0

Views: 288

Answers (2)

SLaks
SLaks

Reputation: 887275

The problem stems from the following potential class:

class FunnyNumber extends Integer { }

This class does not extend Comparable<T>, so it can't be used as the base T.
In other words, extends Comparable<Integer> is not the same as extends Comparable<T>.

Your second class should not be generic at all.
You should only use generics if you want to vary the type parameter.
Here, you want a single fixed type, so you should make a normal non-generic class that extends BinaryTree<Integer>. (or just use BinaryTree<Integer> directly and don't make a separate class at all)

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533472

Integer is final so what you have is

public class BinaryTreeInt extends BinaryTree<Integer>

However the type implies its is int rather than Integer

Upvotes: 2

Related Questions