Can Java store methods in arrays?

后端 未结 5 2159
生来不讨喜
生来不讨喜 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:51

    You cannot store methods directly in arrays. However you can store objects, which implement the same method differently. For example:

    Mover[] moveArray = {new RightMover(), new DownMover() new LeftMover(), new UpMover() };
    for (i = 0; i < 4; i++) {
        while (myWumpus.moveArray[i]) {
            moveArray[i].move();
            generator.updateDisplay();
        }
    }
    

提交回复
热议问题