Java Reference
In-Depth Information
You can use Choices.YES and Choices.NO to access the values of YES and NO fields in the Choices interface.
Listing 17-8 demonstrates how to use the dot notation to access fields of an interface.
Listing 17-8. Accessing Fields of an Interface
// ChoicesTest.java
package com.jdojo.interfaces;
public class ChoicesTest {
public static void main(String[] args) {
System.out.println("Choices.YES = " + Choices.YES);
System.out.println("Choices.NO = " + Choices.NO);
}
}
Choices.YES = 1
Choices.NO = 2
Fields in an interface are always final whether the keyword final is used in its declaration or not. This implies
that you must initialize a field at the time of declaration. You can initialize a field with a compile-time or runtime
constant expression. Since a final field (constant field) is assigned a value only once, you cannot set the value of the
field of an interface, except in its declaration. The following snippet of code generates a compile-time error:
Choices.YES = 5; // A compile-time error
The following snippet of code shows some valid and invalid field declarations for an interface:
/* All fields declarations are valid in the ValidFields interface */
public interface ValidFields {
int X = 10;
// You can use one field to initialize another if the referenced
// field is declared before the one that references it.
int Y = X;
double N = X + 10.5;
boolean YES = true;
boolean NO = false;
// Assuming Test is a class that exists
Test TEST = new Test();
}
/* Examples of invalid field declarations. */
public interface InvalidFields {
int X; // Invalid. X is not initialized
int Y = Z; // Invalid. Forward referencing of Z is not allowed.
int Z = 10; // Valid by itself.
Test TEST; // Invalid. TEST is not initialized, assuming a Test class exists
}
Search WWH ::




Custom Search