user1555754
user1555754

Reputation: 339

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

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

Upvotes: 4

Views: 3142

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533492

Simple question - Is it posible to initalize array in an interface?

Yes.

This works but i want to initialize array by "for" intsruction. Ok thanks for help

That's not a simple question ;)

You can't do this strictly because you can't add a static block to an interface. But you can have a nested class or enum.

IMHO, that could be more confusing than useful as follows:

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;
        }
    }
}

Java 8 allows static methods in interfaces, Java 9 also allows private methods, so we can avoid the nested class/enum using such a method:

public interface I {
    private static int[] getValues() {
        int[] arr = new int[5];
        for(int i=0;i<arr.length;i++)
            arr[i] = i * i;
        return arr;
    }
        
    int[] values = getValues();
}

Upvotes: 7

Roman C
Roman C

Reputation: 1

Yes, it's possible. See the code:

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);
  }
}

Upvotes: 2

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

Firstly, I agreed with existing answers.

Further, I don’t think it’s a good idea to define data in an interface. See "Effective Java":

Item 19: Use interfaces only to define types

The constant interface pattern is a poor use of interface.

To export constants in interface is bad idea.

Upvotes: 1

pap
pap

Reputation: 27614

Yes, but only if it's static. In fact, any variables declared in an interface will automatically be static.

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
}

You can't have static initializers though.

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

Obviously, you can't have constructors in interfaces.

Upvotes: 2

Jesper
Jesper

Reputation: 206796

Why don't you just try it out?

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

Upvotes: 5

Related Questions