Interfaces
Interfaces
Introduction to interfaces
Applying Interfaces
• Any class that implements an interface adheres to the protocol defined by the interface, and
in the process, implements the specification laid down by the interface
Interface ‘lif_salary’
Write code to
Calculate salary
Write code to for India employees
Calculate salary
for US employees
Implements Implements
lif_salary lif_salary
Sheldon Rahul
Sensitivity: Internal & Restricted © 2017 Wipro wipro.com confidential 6
Why interfaces are required ?
Interfaces allow you to implement common behaviors in different classes that are not
related to each other
Interfaces are used to describe behaviors that are not specific to any particular kind of
object, but common to several kind of objects
Defining an interface has the advantage that an interface definition stands apart from any
class or class hierarchy
This makes it possible for any number of independent classes to implement the interface
This is a constraint in class design, as a class cannot achieve the functionality of two or
more classes at a time
Thus, interfaces enable you to create richer classes and at the same time the classes need
not be related
Any variable declared within. an interface is always, by default, public static and final
What is the behavior which is common among the entities depicted in the pictures above?
Requirement : You have to develop 3 classes, Bird, Superman and Aircraft with the condition that all these
classes must have a method called fly().
What is the mechanism, using which you can ensure that the method fly() is implemented in all these classes?
An Abstract class or An Interface?
class A1 implements I1 {
public void m1() {
System.out.println(“In m1 method”);
}
}
class A1 implements I1 {
public void m1() {
System.out.println(“In m1 method”);
}
}
Programming through interfaces helps create software solutions that are reusable, extensible,
and maintainable
One interface can extend one or more interfaces using the keyword extends
When you implement an interface that extends another interface, you should provide
implementation for all the methods declared within the interface hierarchy
Marker Interface is provided as a handle by java interpreter to mark a class, so that it can
provide special behavior to it at runtime
class A1 extends I1 {
public void m1() {
System.out.println(“In m1 method”);
}
}
interface A1 implements I1 {
public void m2();
}
Abstract Classes can have abstract Interfaces can have only method
methods as well as concrete declarations(abstract methods). You
methods. cannot define a concrete method.
Introduction to interfaces
Creating interfaces
Implementing interfaces
Difference between interfaces and abstract classes