Can Java store methods in arrays?

后端 未结 5 2139
生来不讨喜
生来不讨喜 2020-12-31 08:55

Well I wrote some code and all I was doing was for loops, but changing which method I called. I tried using a for loop so it\'d be a bit neater (and out of curiosity to see

5条回答
  •  粉色の甜心
    2020-12-31 09:47

    You can't store methods in arrays in Java, because methods aren't first-class objects in Java. It's a reason some people prefer to use other languages like Python, Scheme, etc.

    The work-around is to create an interface which contains one method, then create four classes implementing that interface - the MoveRight, MoveLeft, etc... classes. Then you can store instances of those classes in your array and call them all the same way.

提交回复
热议问题