9_Interfaces
9_Interfaces
Module 3
Interfaces
CHAPTER 9
Interfaces 2
When no access specifier is included, then default access results, and the
interface is only available to other members of the package in which it is
declared.
Contd…
• 6 other
When it is declared as public, the interface can be used by any
code.
• In this case, the interface must be the only public interface declared in
the file, and the file must have the same name as the interface.
• name is the name of the interface, and can be any valid identifier. Notice
that the methods that are declared have no bodies.
• They must also be initialized. All methods and variables are implicitly
public.
Contd…
7
Contd…
8
Contd… 9
Genral form:
interface Callback
{
void callback(int param);
}
17
•The following example calls the callback( ) method via an interface
reference variable:
class TestIface
{
public static void main(String args[ ])
{
Callback c = new Client();
c.callback(42);
}
}
Here, the class Incomplete does not implement callback( ) and must be
declared as abstract. Any class that inherits Incomplete must implement
callback( ) or be declared abstract itself.
Nested Interfaces
21
An interface can be declared a member of a class or another interface.
Such an interface is called a member interface or a nested interface.
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
AskMe.java
class AskMe implements SharedConstants {
class Question implements static void answer(int result) {
SharedConstants { switch(result) {
Random rand = new Random(); case NO:
System.out.println("No");
int ask() {
break;
int prob = (int) (100 *rand.nextDouble());
case YES:
if (prob < 30) System.out.println("Yes");
return NO; // 30% break;
else if (prob < 60) case MAYBE:
return YES; // 30% System.out.println("Maybe");
else if (prob < 75) break;
return LATER; // 15% case LATER:
else if (prob < 98) System.out.println("Later");
return SOON; // 13% break;
case SOON:
else
System.out.println("Soon");
return NEVER; // 2% break;
} case NEVER:
} System.out.println("Never");
break;
}
}
AskMe.java
29
The answer is, essentially, no. Recall that there is still a key
difference between a class and an interface: a class can
maintain state information (especially through the use of
instance variables), but an interface cannot.
default methods do offer a bit of what one would normally
associate with the concept of multiple inheritance.
general form:
InterfaceName.staticMethodName
Example