Using the marker interface to limit a common parameter

I have a Foo class that can handle a specific type of variable. I want to limit this type to the few classes that I have. These classes have been implemented, but do not have any inheritance relationships. Does it make sense to write an empty Type interface and then add 'implements Type' to all classes that are the accepted type for the general parameter T.

This would mean that you would get something like this:

public class SuperFoo() {
    //Some code
}

public class Foo<T extends Fooable> extends SuperFoo {
    private T acceptedObject;
    private String name;

    public Foo(String name, T acceptedObject) {
        this.name = name;
        this.acceptedObject = acceptedObject;
        //Some code
    }
}

public interface Fooable {}

public class FooableClass1 implements Fooable {  //Objects of this class will be accepted as T
    public FooableClass1() {}
    //Some code
}

public class FooableClass2 implements Fooable { //Object of this class will also be accepted as T
    public FooableClass1() {}
    //Some code
}

public class AnotherClass { //Objects of this class will not be accepted as T
    //Some code
}

EDIT: Thanks for the answers already, I changed the code above. I have an additional question for this piece of code. If I wanted to implement a method in another class that creates a new instance of the SuperFoo class (Foo superclass), how would I do it?

This method will look something like this:

public SuperFoo createNewFoo(String name, Type type) {
    //Calls the constructor of Foo and returns the object but how?
    //The type parameter decides whether the constructor of FooableClass1 
    //or the constructor of FooableClass2 is called.
}

Type? , Fooable .

+4
1

interface Fooable. Serializable java api, , .

0

Source: https://habr.com/ru/post/1589451/


All Articles