Differences Between Classes and Interfaces, Implementing Interfaces
Differences Between Classes and Interfaces, Implementing Interfaces
Differences Between Classes and Interfaces, Implementing Interfaces
interfaces,
Implementing Interfaces
Interface
• 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.
Interface-cont…
• In practice, this means that you can define
interfaces that 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.
Interface-cont…
• 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.
Interface-cont…
• Interfaces are designed to support dynamic
method resolution at run time.
• Normally, in order for a method to be called
from one class to another, both classes need
to be present at compile time so the Java
compiler can check to ensure that the method
signatures are compatible.
Interface-cont…
• This requirement by itself makes for a static
and non extensible classing environment.
• Inevitably in a system like this, functionality
gets pushed up higher and higher in the class
hierarchy so that the mechanisms will be
available to more and more subclasses.
• Interfaces are designed to avoid this problem.
Interface
• They disconnect the definition of a method or
set of methods from the inheritance hierarchy.
• Since interfaces are in a different hierarchy
from classes, it is possible for classes that are
unrelated in terms of the class hierarchy to
implement the same interface.
• This is where the real power of interfaces is
realized.
Defining an Interface
• An interface is defined much like a class. This is the
general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Defining an Interface-cont...
End of session