Are public members variables in Java 8 interfaces a feature or an implementation side-effect/defect?
This question pertains to the pre-release Java 8 build lambda-8-b50-linux-x64-26_jul_2012.tar.gz.
Java 8 introduces new features to interfaces in the form of default methods. Casual testing with the JDK8 lambda compiler allows interfaces of this form:
public interface Foo {
public int foo = 0;
int foo() default { return foo; }
}
Sample implementing type:
public class FooImpl implements Foo {
public int foo = 1;
}
This code follows the standard conventions for variable shadowing:
Foo f = new FooImpl();
System.out.println(f.foo());
System.out.println(f.foo);
System.out.println(new FooImpl().foo);
Output:
0
0
1
The documentation (JSR 335: Lambda Expressions for the Java™ Programming Language Version 0.5.1) doesn't mention member variables. I'm inclined to think the compiler is being too tolerant but perhaps I've missed something.
The class cannot contain abstract methods. Interfaces contain only abstract methods. The class can have variables and methods that are default, public, private, or protected. The interface has only public variables and methods by default.
Yes, Interfaces CAN contain member variables. But these variables have to be implicitly (without any keyword definition) final, public and static. This means that within interfaces, one can only declare constants. You cannot declare instance variables using interfaces.
No you can not declare variable in interface. No, we can't declare variables, constructors, properties, and methods in the interface.
Prior to java 8, interface in java can only have abstract methods. All the methods of interfaces are public & abstract by default. Java 8 allows the interfaces to have default and static methods.
Public fields in interfaces are not a new features in Java 8. If you remember that they are implicitly static and final, the results you are seeing make perfect sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With