Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 (pre-release) interface member variables

Tags:

java

java-8

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.

like image 514
McDowell Avatar asked Aug 27 '12 22:08

McDowell


People also ask

Can Java 8 interface have variables?

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.

Can an interface have member variables Java?

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.

Can we declare member variables in interface?

No you can not declare variable in interface. No, we can't declare variables, constructors, properties, and methods in the interface.

What does an interface contain before jdk8?

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.


1 Answers

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.

like image 95
TimK Avatar answered Oct 05 '22 22:10

TimK