Java Reference
In-Depth Information
The following declaration of the
Runner
interface uses a
@FunctionalInterface
annotation. The interface
declaration will compile fine.
@FunctionalInterface
public interface Runner {
void run();
}
The following declaration of the
Job
interface uses a
@FunctionalInterface
annotation, which will generate
a compile-time error because the
Job
interface declares two abstract methods, and therefore it is not a functional
interface.
@FunctionalInterface
public interface Job {
void run();
void abort();
}
The following declaration of the
Test
class uses a
@FunctionalInterface
annotation, which will generate a
compile-time error because a
@FunctionalInterface
annotation can only be used on interfaces.
@FunctionalInterface
public class Test {
public void test() {
// Code goes here
}
}
■
an interface with only one abstract method is always a functional interface whether it is annotated with a
@FunctionalInterface
annotation or not. Use of the annotation instructs the compiler to verify the fact that the
interface is really a functional interface.
Tip
Annotating a Java Package
Annotating program elements such as classes and fields are intuitive, as you annotate them when they are declared.
How do you annotate a package? A package declaration appears as part of a top-level type declaration. Further, the
same package declaration occurs multiple times at different places. The question arises: how and where do you
annotate a package declaration?
You need to create a file, which should be named
package-info.java
, and place the annotated package declaration
in it. Listing 1-17 shows the contents of the
package-info.java
file. When you compile the
package-info.java
file,
a class file will be created.
Listing 1-17.
Contents of a package-info.java File
// package-info.java
@Version(major=1, minor=0)
package com.jdojo.annotation;