简体   繁体   中英

How to create an instance of an abstract class that passes an interface into its constructor?

Right now, I have a generic class USetSet<T> that extends AbstractSet<T> that I want to invoke. It may me important to note that USetSet<T> 's constructor takes in an interface USet<T> . The class USetSet<T> is as follows:

package bag_assignment1;

import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class USetSet<T> extends AbstractSet<T> {
    USet<T> s;

    public USetSet(USet<T> s) {
        this.s = s;
    }

    @SuppressWarnings("unchecked")
    public boolean contains(Object x) {
        return s.find((T)x) != null;
    }

    public boolean add(T x) {
        return s.add(x);
    }

    @SuppressWarnings("unchecked")
    public boolean remove(Object x) {
        return s.remove((T)x) != null;
    }

    public Iterator<T> iterator() {
        return s.iterator();
    }

    public int size() {
        return s.size();
    }

    public void clear() {
        s.clear();
    }
}

For reference, the USet<T> interface is:

package bag_assignment1;

public interface USet<T> extends Iterable<T> {
    public int size();
    public boolean add(T x);
    public T remove(T x);
    public T find(T x);
    public void clear();
}

And right now, in another class I am trying to create an insance of USetSet<T> . Normally, this syntax would work with generics in my project using Integers to pass into.

USetSet<Integer> coolBag=new USetSet<Integer>(Integer.class);

However, I don't know if I need to pass in a USet<T> into USetSet<T> in this case to make it work. Is there a way I can create an instance of USetSet<T> ?

Trivially, you can create it using new USetSet<>(null) . Of course, it fails whenever you call one of the instance methods...

So instead, just create a class which implements the USet interface, and pass that in, eg

new USetSet<>(new USet<Integer>() {
  // Implement methods.
})

Or:

class USetImpl implements USet<Integer> {
  // Implement methods.
}

new USetSet<>(new USetImpl())

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