Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable implementing two interfaces

I've seen a number of similar questions, but I don't think any were quite isomorphic, and none quite answered my question.

Suppose there are two interfaces, Tree and Named. Suppose further that I am given a method whose signature is

public <T extends Tree & Named> T getNamedTree();

How can I save the returned value to a variable, while still retaining the information that it implements both Tree and Named? I can't find a way of declaring a variable like

public <T extends Tree & Named> T mNamedTree;

and trying to cast it to an interface extending Tree and Named results in a class cast exception.

like image 903
Erhannis Avatar asked Apr 20 '17 23:04

Erhannis


2 Answers

Assuming there is no third interface inheriting both Named and Tree, you cannot retain information about both interfaces statically. The compiler will require you to do a cast for one or the other, or for both:

Object namedTree = getNamedTree();
Tree asTree = (Tree)namedTree;
Named asNamed = (Named)namedTree;

Both casts should succeed.

If you have influence on the design of the API for the class, ask the authors to introduce an interface combining both Named and Tree, and returning an instance of that interface instead.

like image 146
Sergey Kalinichenko Avatar answered Sep 22 '22 15:09

Sergey Kalinichenko


One possible solution would be to create another interface that extends both Tree and Named, and simply store that as the variable:

interface NamedTree extends Tree, Named {

}

public NamedTree namedTree;

public NamedTree getNamedTree();
like image 38
Jacob G. Avatar answered Sep 26 '22 15:09

Jacob G.