Java equivalent of function mapping in Python

前端 未结 7 1446

In python, if I have a few functions that I would like to call based on an input, i can do this:

lookup = {\'function1\':function1, \'function2\':function2, \'fu         


        
7条回答
  •  名媛妹妹
    2021-02-04 15:50

    Polymorphic example..

    public interface Animal {public void speak();};
    public class Dog implements Animal {public void speak(){System.out.println("treat? treat? treat?");}}
    public class Cat implements Animal {public void speak(){System.out.println("leave me alone");}}
    public class Hamster implements Animal {public void speak(){System.out.println("I run, run, run, but never get anywhere");}}
    
    Map animals = new HashMap();
    animals.put("dog",new Dog());
    animals.put("cat",new Cat());
    animals.put("hamster",new Hamster());
    for(Animal animal : animals){animal.speak();}
    

提交回复
热议问题