A variable that implements two interfaces

I saw a number of similar questions, but I do not think they were isomorphic, and no one answered my question.

Suppose that there are two interfaces: Treeand Named. Suppose further that I have been given a method whose signature

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

How to save the return value of a variable, while maintaining the information that it implements both Tree, and Named? I cannot find a way to declare a variable of type

public <T extends Tree & Named> T mNamedTree;

and attempt to pass it on to the expansion interface Treeand Namedleads to the exclusion of class.

+4
source share
3 answers

What area should the variable have?

There are three possibilities.

A) . ... :

interface ItfA { Number propA(); };
interface ItfB { Number propB(); };

class Main {

  private <T extends ItfA & ItfB> T getT() {
     return null;
  }

  private <TT extends ItfA & ItfB> void doStuffWithT() {
     TT theT = getT();
     System.err.println(theT.propA());
     System.err.println(theT.propB());
  }

}

B) - , . generic &:

interface ItfA { Number propA(); };
interface ItfB { Number propB(); };

class Main<T extends ItfA & ItfB> {

  T theT;

  public void setT(T newT) {
     theT = newT;
  }

  public void doStuffWithT() {
     System.err.println(theT.propA());
     System.err.println(theT.propB());
  }

}

C) - , . generics.

C.1) , , , , .

C.2) , , , ItfA ItfB. , ItfAB. .

C.3) , ? , ?

, :

C.3.a) Object, ItfA ItfB ( ).

C.3.b) , , -, , "T". - , <T extends ItfA & ItfB> ( B.).

0

, , Named, Tree, . , :

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

.

API , , Named, Tree, .

+3

interface, extends Tree, Named, :

interface NamedTree extends Tree, Named {

}

public NamedTree namedTree;

public NamedTree getNamedTree();
+1

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


All Articles