Java - 接口不允许 ArrayList 正常运行

EML*_*EML -4 java interface arraylist

我正在尝试实现一个名为 board 的接口,Board但是每当我尝试向其中创建的 ArrayList 添加任何内容时,它都会抛出

- Syntax error on token(s), misplaced construct(s) - Syntax error on token "Tile1", VariableDeclaratorId expected after this token

这是完整的代码:

import java.util.ArrayList;


public interface BoardTest {
    public ArrayList<Land> lands = new ArrayList<Land>();

    Land Tile1 = new Land(0,1,0,0,0, "Tile 1");
    lands.add(Tile1);
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

duf*_*ymo 5

接口不能有实现。

您不能在接口中创建 ArrayList 或调用其任何方法。您所能做的就是为一个方法创建一个方法签名,该方法可能会或可能不会按照您编写的方式进行操作。

界面的整个想法是将“什么”与“如何”分开。

也许你的意思是:

public interface Board {
    void land(Land l);
}

public class BoardImpl implements Board {
   List<Land> squares = new ArrayList<Land>();

   public void land(Land l) {
      this.squares.add(l);
   }
}
Run Code Online (Sandbox Code Playgroud)