简体   繁体   中英

Java: How to create an instance of a generic class that implements an abstract interface?

Right now, I am trying to create an instance of a generic class BTree<T> which implements an interface SSet<T> which in turn implements Iterable<T> I've deleted the bulk of the code out of the BTree<T> class and left only the constructor. Though, if it's essential, I can add the entire code if anyone believes it is helpful. The BTree<T> class looks something like this:

package assignment2_draft;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

public class BTree<T> implements SSet<T> {

    //Some methods

    public BTree(int b, Class<T> clz) {
    this(b, new DefaultComparator<T>(), clz);
    }

}

In my own class, I am trying to call the BTree<T> class and pass an Integer into the generic. In my class, I have:

BTree<Integer> myTree=new BTree<Integer>(Integer.class);

which has worked in generic classes before, but not this class. I am wondering, am I passing in the parameters right? Or do I need to somehow reference SSet<T> when creating an instance of BTree<T>

Your constructor signature is BTree(int, Class<T>)

So it would seem you need to do something like

SSet<Integer> tree = new BTree<Integer>(2, Integer.class);

Notice the reference is an SSet<> not a BTree<> - you COULD use a BTree<> reference there, if you wanted, but in general it's preferable to program to an interface unless you have a reason not to.

Your Constructor which you provided above, accept two value

public BTree(int b, Class<T> clz) {
this(b, new DefaultComparator<T>(), clz);
}

but you are providing only one,

BTree<Integer> myTree=new BTree<Integer>(Integer.class);

does do you have any other constructor ,If not then use following

int a=5; 
SSet<Integer> myTree=new BTree<Integer>(a,Integer.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM