Java 在接口内声明数组对象

Java 在接口内声明数组对象,java,Java,我有这样的场景,它是否是一个好的实现 public interface Vehicle { // is it possible to declare array in interface? //so it is possible and no compilation errors Vehicle[] vehicles1 = new Vehicle[10]; } 从技术上讲,可以声明这样的字段。它将是公共的,静态的和最终的(这基本上使它成为一个常量),即使您没有明确地声明它 这是否是一个

我有这样的场景,它是否是一个好的实现

public interface Vehicle {
// is it possible to declare array in interface?

//so it is possible and no compilation errors

Vehicle[] vehicles1 = new Vehicle[10];


}

从技术上讲,可以声明这样的字段。它将是
公共的
静态的
最终的
(这基本上使它成为一个常量),即使您没有明确地声明它


这是否是一个好的实践实际上取决于你将使用它做什么。但是,在大多数情况下不鼓励使用该属性。

您可以这样做,但该属性是公共的,这不是一种好的样式。属性应该是私有的,并由
getter
setter
方法访问。

否,您只能在接口中声明
public
方法和
静态final
字段(常量)

这样的事情是可能的,但不是你想要的:

public interface Vehicle {
    public static final Vehicle[] vehicles1 = new Vehicle[10];
}
我建议使用通常的
get
set
模式:

public interface Vehicle {
    void setVehicles1(Vehicle[] vehicles);
    Vehicle[] getVehicles1();
}

您可以像
Vehicle[]vehicles1=新车[10]那样声明它
-
public
static
final
修饰符将被隐式添加对此不确定(因为op建议他出现编译错误)。定义存储类型属于实现细节,您不应该在接口中这样做,接口只关心声明行为(没有定义它)。