简体   繁体   中英

Java method that returns interface type

As I was reading about java interface, I came across the following example. I know how to implement an interface. But returning interface type in a method is something new to me. Could someone help me to understand this example? Will the methods in the "Animal" interface be implemented in the "categorizeAnimals" method? If yes, the "animals" array will be passed into all the interface methods in the "categorizeAnimals" method?

public class Wild {

  public static interface Animal {
      public List<String> getInvertebrates();
      public List<String> getFishes();
      public List<String> getAmphibians();
      public List<String> getReptiles();
  }


  public static Animal categorizeAnimals(String[] animals) {
    .......
    .......
    .......
    return null;
  }
}

Appreciate your reply, Thanks much.

A reference to an interface can represent a value of any type that implements that interface, and only of those types.

As others have said, the fragment you're showing us seems a bit incoherent, so I'm not going to try to explain it -- let's try this instead:

If we say Bear , Trout , and Mosquito are the subclasses of Animal , a function which returns Animal could return an instance of any of those types -- just as a function which takes an Animal as a parameter could accept instances of any of those via that parameter.

(This is actually a bad example -- Bear, Trout, and Mosquito are more likely to be instances, with the types being things like Mammal, Fish, and Insect -- but you get the idea.)

categorizeAnimals方法的主体中,您的返回类型应该是已实现的类的实例Animal接口

very simple solution is that if you have put any interface into the any of the method then then what ever class instance you are returning that class has to have that interface implemented.

public class ImplementedClass implements Interfacename {

    @Override
    public void sayhi(String hello) {
        // TODO Auto-generated method stub

    }

    @Override
    public void sayhello() {
        // TODO Auto-generated method stub

    }

    public Interfacename sayhello1() {
        System.out.println("returning new intance of class which is implementing that interface");
        return new ImplementedClass();
    }
}

interface is

public interface Interfacename {
    public void sayhi(String hello);

    public void sayhello();

}

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