L10.1 - Interface
L10.1 - Interface
interface
• An interface in java is a blueprint of a class.
• It has static constants and abstract methods.
• It cannot be instantiated just like abstract class.
• It is used to achieve abstraction and multiple inheritance in Java.
• Since Java 8, interface can have default and static methods.
Properties of interfaces
• The interface keyword is used to declare an interface.
• Variable in an interface are implicitly public, static & final (and have to be
assigned values there).
interface
• interface fields are public, static and final by default, and methods are
public and abstract.
Implementing interfaces
• When a class implements an interface, then it has to perform the specific behaviors
of the interface.
• If a class does not perform all the behaviors of the interface, the class must declare
itself as abstract.
• The implements keyword appears in the class declaration following the extends
portion of the declaration.
Example 1 (implementing interface)
Example 2 (members accessibility)
Example 3 (Bank)
Exercise
• Wap to create an interface named Shape containing method:
• double getArea()
• Now create a class named Rectangle which inherits Shape and contains instance variables: length, width
which are initialized using parameterized constructor.
• Also create another class named Circle which also inherits Shape and contains instance variable: radius
which is initialized using parameterized constructor.
• Now create another class Test containing main() method where you have to create an object of both
Rectangle and Circle (and initialize their values using parameterized constructor).
• This class also contains another method named calculate() which will be used to print the area of any object
passed to it.
• Call this calculate() method inside main() twice such that during the first call you have to pass Circle object
and during the second call you have to pass Rectangle object.
Solution
Exercise
• Write a program to implement interface Colors having methods:
void setColor(String color)
String getColor()
• Create a class Square which implements the Colors interface and having
private attributes: side & color and methods:
void setSide(double side)
double getSide()
double getArea()
• Create a class Test having main() method in which you have to create an
object of Square class and display its area & details after taking input from
user at runtime.
interface vs. class
An interface is similar to a class in the following ways:
• An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.