Java Mod 3 Interfaces
Java Mod 3 Interfaces
ES
INTERFACES
• Using the keyword interface, you can fully abstract a class’ interface from its
implementation.
• That is, using interface, you can specify what a class must do, but not how it does it.
• Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body.
• In practice, this means that you can define interfaces which don’t make assumptions
about how they are implemented.
• Once it is defined, any number of classes can implement an interface.
• Also, one class can implement any number of interfaces.
• To implement an interface, a class must create the complete set of methods defined by
the interface.
• However, each class is free to determine the details of its own implementation.
• By providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
Defining an Interface
• General form of an interface: • Notice that the methods which are declared have
no bodies. They end with a semicolon after the
parameter list.
• They are, essentially, abstract methods; there can
be no default implementation of any method
specified within an interface.
• Each class that includes an interface must
implement all of the methods.
• Variables can be declared inside of interface
declarations. They are implicitly final and static,
meaning they cannot be changed by the
implementing class.
• They must also be initialized with a constant
value.
• Here, access is either public or • All methods and variables are implicitly public if
not used. the interface, itself, is declared as public.
interface Callback {
• name is the name of the interface,
void callback(int param);
and can be any valid identifier.
}
Implementing Interfaces
• Once an interface has been
defined, one or more classes can
implement that interface.
• To implement an interface,
include the implements clause in
a class definition, and then create
the methods defined by the
interface.
• General form of a class that
includes the implements clause
looks like this:
Accessing Implementations Through Interface
References
// Implement MyIF.
class MyIFImp implements MyIF {
// Only getNumber() defined by MyIF needs to be
implemented.
// getString() can be allowed to default.
public int getNumber() {
return 100;
}
}
The following code creates an instance of MyIFImp and uses it to call both getNumber( ) and
getString( ).
// Use the default method.
class DefaultMethodDemo {
public static void main(String[] args) {
MyIFImp obj = new MyIFImp();
// Can call getNumber(), because it is explicitly
// implemented by MyIFImp:
System.out.println(obj.getNumber());
// Can also call getString(), because of default
// implementation:
System.out.println(obj.getString());
}
}