Is it possible to initialize an array in an interface?

Is it possible to initialize an array in an interface using a command for?

+5
source share
5 answers

A simple question: is it possible to initialize an array in an interface?

Yes.

This works, but I want to initialize the array on a for basis. Ok thanks for the help

This is not an easy question;)

You cannot do this strictly because you cannot add a static block to the interface. But you can have nested classor enum.

IMHO, this may be more confusing than useful:

public interface I {
    int[] values = Init.getValue();

    enum Init {;
        static int[] getValue() {
            int[] arr = new int[5];
            for(int i=0;i<arr.length;i++)
                arr[i] = i * i;
            return arr;
        }
    }
}
+6
source

Why don't you just give it a try?

public interface Example {
    int[] values = { 2, 3, 5, 7, 11 };
}
+4
source

, . , , , .

public interface ITest {
    public static String[] test = {"1", "2"}; // this is ok
    public String[] test2 = {"1", "2"}; // also ok, but will be silently converted to static by the compiler
}

.

public interface ITest {
    public static String[] test;
    static {
        // this is not OK. No static initializers allowed in interfaces.
    }
}

, .

+2

, . :

public interface Test {
  int[] a= {1,2,3};
}

public class Main {
  public static void main(String[] args) {

    int i1 = Test.a[0];
    System.out.println(i1);
  }
}
+2

First, I agreed with the existing answers.

Also, I don't think it is a good idea to define data in an interface. See Effective Java:

Item 19: Use Interfaces Only for Type Definitions

A persistent interface template makes poor use of the interface.

Exporting constants to an interface is a bad idea.

+1
source

All Articles