Constructor in an Interface

All fields in an Interface are implicitly final and staticNow, i know final variables have to be initialised by the constructor, if not initialised in the definitionSo, why no allow a constructor for an interface just to initialize the final variables?
[273 byte] By [enterneoa] at [2007-11-27 9:22:23]
# 1

You can set default values by doing something like the following:

public final int finalInteger = 12345;

There are no constructors in an interface because they are not objects, they are interfaces. I can't imagine why you would really need to set default values in an interface anyway as each class that implements that interface would be using it for different purposes and in different ways. You should just add code to set the values in the constructor of the class that implements it.

RedUnderTheBeda at 2007-7-12 22:16:47 > top of Java-index,Java Essentials,New To Java...
# 2

> anyway as each class that

> implements that interface would be using it for

> different purposes and in different ways. You should

> just add code to set the values in the constructor of

> the class that implements it.

ok i tried this

interface A

{

int x;// error - final uninitialized

int y=5;// error - final is reinitialised in Demo()

}

class Demo implements A

{

Demo()

{

x = 10;

y = 10;

}

public static void main(String args[])

{

Demo d = new Demo();

System.out.println(x);

}

}

enterneoa at 2007-7-12 22:16:47 > top of Java-index,Java Essentials,New To Java...
# 3

> Now, i know final variables have to be initialised by

> the constructor, if not initialised in the

> definition

Not final static fields. Constructors should NOT be setting static fields.

> So, why no allow a constructor for an interface just

> to initialize the final variables?

Because they're static.

jverda at 2007-7-12 22:16:47 > top of Java-index,Java Essentials,New To Java...