StrikeAgainst
StrikeAgainst

Reputation: 634

How to refer to an instance that both extends and implements?

Let's say I have an abstract class, an extending class, and an interface like this:

public abstract class SuperClass {
    ...
    public void foo() {...}
    ...
}

public class SubClass extends SuperClass implements MyInterface {...}

public interface MyInterface {
    public void bar();
}

Note that I have a few subclasses of SuperClass implementing MyInterface, but not all of them. Also let's say, I have another class with a constructor like this:

public class AnotherClass {
    private SuperClass sc;
    public AnotherClass(SuperClass superclass) {
        sc = superclass;
    }
    ...
}

My question now is, how would I be able to ensure that the given object in the constructor also implements MyInterface? I would need the object sc to be able to run both methods foo() and bar(). How can I accomplish this?

Upvotes: 1

Views: 72

Answers (3)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23339

You can use generics with intersection types,

public class AnotherClass<T extends SuperClass & MyInterface> {
private T sc;
public AnotherClass(T superclass) {
    sc = superclass;
}
void fn(){
 // use both methods
 sc.foo();
 sc.bar();
}
...
}

Now, AnotherClass will only allow types that are SuperClass and implement MyInterface.

Upvotes: 3

Andr&#233; Stannek
Andr&#233; Stannek

Reputation: 7863

You could introduce another class to the hierachy:

public class NonImplementingSubClass extends SuperClass {...}

public class ImplementingSubClass extends SuperClass implements MyInterface {...}

All your subclasses that should implement your interface, will then extend ImplementingSubClass

public class SubClass extends ImplementingSubClass {...}

public class AnotherClass {
    private ImplementingSubClass sc;
    public AnotherClass(ImplementingSubClass superclass) {
        sc = superclass;
    }
    ...
}

Upvotes: 3

ACV
ACV

Reputation: 10560

public abstract class SuperClass implements MyInterface {
    ...
    public void foo() {...}
    ...
}

public class SubClass extends SuperClass{}

public interface MyInterface {
    public void bar();
}

Upvotes: 0

Related Questions