OBJECT-ORIENTED PROGRAMMING
THROUGH JAVA
UNIT - III
Session 19 - Interfaces - Part 1
1. Introduction
Introduction
What are Interfaces in Java?
In Java, an interface is an abstract type used to specify the behavior of a class. An interface in
Java acts as a blueprint for a class, specifying what methods a class should implement but not
how these methods should be implemented. Interfaces are a key mechanism for achieving
abstraction in Java, allowing you to define methods that other classes must implement.
Key Characteristics of Interfaces:
● Abstraction: Interfaces provide a way to achieve abstraction. They allow you to define
methods without implementing them, letting other classes provide the actual
implementation.
● Multiple Inheritance: Java does not support multiple inheritance with classes. However,
a class can implement multiple interfaces, thereby achieving multiple inheritance.
● No Instantiation: Interfaces cannot be instantiated on their own. They must be
implemented by classes.
Example:
Consider a scenario where you have different types of vehicles, like bicycles and cars, which
share common functionalities. Instead of defining these functionalities separately in each vehicle
class, you can define an interface with these methods and let each vehicle class implement the
interface.
2. Declaration of Interface
Declaration of Interface
Syntax
To declare an interface in Java, use the interface keyword. The syntax is as follows:
interface InterfaceName {
// Declare constants (public, static, final by default)
int CONSTANT = 100;
// Declare methods (public and abstract by default)
void method1();
void method2();
}
Example:
interface Vehicle {
void start();
void stop();
}
In this example, Vehicle is an interface with two abstract methods: start() and stop().
Any class that implements the Vehicle interface must provide implementations for these
methods.
Features of Interfaces:
● Method Declaration: Methods in an interface are implicitly public and abstract (in
earlier versions of Java). This means they do not have a body.
● Field Declaration: Fields in an interface are public, static, and final by default.
They must be initialized when declared.
● No Constructors: Interfaces cannot have constructors because they cannot be
instantiated.
● No Instance Variables: Interfaces cannot contain instance variables.
3. Implementation of Interface
Implementation of Interface
Syntax
To implement an interface, use the implements keyword. A class that implements an interface
must provide concrete implementations for all the methods declared in the interface.
class ClassName implements InterfaceName {
// Implement the methods of the interface
@Override
public void method1() {
// Method implementation
}
@Override
public void method2() {
// Method implementation
}
}
Example:
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started.");
}
@Override
public void stop() {
System.out.println("Car stopped.");
}
}
public class Test {
public static void main(String[] args) {
Car myCar = new Car();
myCar.start();
myCar.stop();
}
}
Output:
Car started.
Car stopped.
Real-World Example:
Consider the example of vehicles with common functionalities like changing gear, speeding up,
and applying brakes. We can define an interface Vehicle with these methods and then
implement this interface in classes like Bicycle and Bike.
Code Example:
interface Vehicle {
void changeGear(int gear);
void speedUp(int increment);
void applyBrakes(int decrement);
}
class Bicycle implements Vehicle {
int speed = 0;
int gear = 0;
@Override
public void changeGear(int newGear) {
gear = newGear;
}
@Override
public void speedUp(int increment) {
speed += increment;
}
@Override
public void applyBrakes(int decrement) {
speed -= decrement;
}
public void printStates() {
System.out.println("Speed: " + speed + " Gear: " + gear);
}
}
class Bike implements Vehicle {
int speed = 0;
int gear = 0;
@Override
public void changeGear(int newGear) {
gear = newGear;
}
@Override
public void speedUp(int increment) {
speed += increment;
}
@Override
public void applyBrakes(int decrement) {
speed -= decrement;
}
public void printStates() {
System.out.println("Speed: " + speed + " Gear: " + gear);
}
}
public class Main {
public static void main(String[] args) {
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
System.out.println("Bicycle state:");
bicycle.printStates();
Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);
System.out.println("Bike state:");
bike.printStates();
}
}
Output:
Bicycle state:
Speed: 2 Gear: 2
Bike state:
Speed: 1 Gear: 1
Advantages of Interfaces:
1. Abstraction: Interfaces help in achieving abstraction by hiding the implementation
details from the user.
2. Multiple Inheritance: Interfaces allow a class to inherit from multiple sources, which is
not possible with classes alone.
3. Loose Coupling: Interfaces help in achieving loose coupling by defining methods that
can be implemented differently by various classes.
New Features in JDK 8 and Beyond:
- Default Methods: Interfaces can now have default methods with an implementation.
This allows you to add new methods to interfaces without breaking existing
implementations.
interface MyInterface {
default void defaultMethod() {
System.out.println("Default method in interface");
}
}
Static Methods: Interfaces can now have static methods that can be called
independently of an object.
interface MyInterface {
static void staticMethod() {
System.out.println("Static method in interface");
}
}
Private Methods: JDK 9 introduced private methods in interfaces, allowing better code
organization within the interface.
interface MyInterface {
private void privateMethod() {
// Implementation
}
default void defaultMethod() {
privateMethod();
}
}
Extending Interfaces
An interface can extend another interface. When a class implements an interface that extends
another interface, it must provide implementations for all methods from the parent interfaces.
Example:
interface A {
void method1();
void method2();
}
interface B extends A {
void method3();
}
class MyClass implements B {
@Override
public void method1() {
System.out.println("Method 1");
}
@Override
public void method2() {
System.out.println("Method 2");
}
@Override
public void method3() {
System.out.println("Method 3");
}
}
Output:
Method 1
Method 2
Method 3
● Interfaces in Java are a way to achieve abstraction and multiple inheritance.
● They contain abstract methods that must be implemented by the classes that use them.
● Interfaces can also have default and static methods since JDK 8 and private methods
since JDK 9.
● They cannot be instantiated on their own but can be used as references to objects of
implementing classes.
Do It Yourself
1. Define an interface Appliance with methods turnOn() and turnOff(). Implement
this interface in classes WashingMachine and Refrigerator.
2. Write an interface Vehicle with methods accelerate() and brake(). Implement
this interface in classes Bike and Car.
3. Define an interface Shape with methods area() and perimeter(). Implement this
interface in Square and Triangle.
4. Create an interface PaymentGateway with methods initiateTransaction() and
confirmTransaction(). Implement this interface in classes Stripe and PayPal.
5. Design an interface Student with methods getName() and getGrade(). Implement
this interface in classes Undergraduate and Postgraduate.
Quiz
1. What keyword is used to define an interface in Java?
A) interface
B) class
C) abstract
D) implements
Answer: A) interface
2. Which of the following can be defined in an interface?
A) Constructors
B) Instance variables
C) Abstract methods
D) Instance methods with a body
Answer: C) Abstract methods
3. Given the following code, what will be the output?
public interface Example {
void show();
default void display() {
System.out.println("Display method");
}
}
public class Test implements Example {
public void show() {
System.out.println("Show method");
}
public static void main(String[] args) {
Test obj = new Test();
obj.show();
obj.display();
}
}
A) Show method
B) Display method
C) Show method
D) Show method Display method
Answer: D) Show method Display method
4. Can a class implement multiple interfaces?
A) Yes
B) No
C) Only if they are not conflicting
D) Only if one interface extends another
Answer: A) Yes
5. Which method of an interface can be called without creating an instance of the
interface?
A) Abstract method
B) Default method
C) Static method
D) Constructor
Answer: C) Static method
4. Multiple Interfaces
Here is a detailed reading material on "Multiple Interfaces in Java" tailored for engineering
students:
Multiple Interfaces in Java
Introduction
In Java, a class can implement multiple interfaces. This feature allows a class to inherit from
more than one source, providing a way to achieve multiple inheritance of type. This is
particularly useful in scenarios where a class needs to implement various functionalities that can
be abstracted into different interfaces.
Why Use Multiple Interfaces?
1. Multiple Inheritance: Java does not support multiple inheritance with classes, but
multiple inheritance is achieved through interfaces.
2. Modularity: It allows for modular design by splitting functionalities into different
interfaces.
3. Flexibility: A class can implement various behaviors by implementing multiple
interfaces, making it versatile.
Syntax
To implement multiple interfaces, use a comma-separated list in the implements clause of the
class declaration.
class ClassName implements Interface1, Interface2, Interface3 {
// Implement all methods from Interface1, Interface2, and Interface3
}
Example
Consider two interfaces: Vehicle and Electric:
interface Vehicle {
void start();
void stop();
}
interface Electric {
void charge();
}
A class ElectricCar implementing both interfaces would look like this:
class ElectricCar implements Vehicle, Electric {
@Override
public void start() {
System.out.println("Electric car started.");
}
@Override
public void stop() {
System.out.println("Electric car stopped.");
}
@Override
public void charge() {
System.out.println("Charging electric car.");
}
}
In the main method, you can test the ElectricCar class:
public class Test {
public static void main(String[] args) {
ElectricCar myCar = new ElectricCar();
myCar.start();
myCar.charge();
myCar.stop();
}
}
Output:
Electric car started.
Charging electric car.
Electric car stopped.
Explanation
- Interface Implementation: The ElectricCar class implements both Vehicle and
Electric interfaces. It must provide concrete implementations for all the methods
declared in these interfaces.
- Multiple Interface Implementation: The class demonstrates how a single class can
take on multiple behaviors by implementing different interfaces.
Visual Representation
(Note: Replace the URL with a real image link or use a suitable diagram representing multiple
interfaces in Java.)
Practice Programs
1. Example 1: Implement two interfaces Animal and Pet. Create a class Dog that
implements both interfaces and provides implementations for the methods.
2. Example 2: Define an interface Person with methods eat() and sleep(). Define
another interface Worker with methods work() and rest(). Create a class
Engineer that implements both interfaces.
Simple Homework Questions
1. Homework Question 1:
Do It Yourself
1. Define two interfaces: Appliance and SmartDevice. The Appliance interface
should have methods turnOn() and turnOff(). The SmartDevice interface should
have methods connect() and disconnect(). Create a class
SmartWashingMachine that implements both interfaces.
2. Create an interface Vehicle with methods accelerate() and brake(). Create
another interface Electric with a method charge(). Implement both interfaces in a
class ElectricScooter.
3. Define two interfaces: Player with methods play() and pause(), and Recorder
with a method record(). Implement both interfaces in a class MultimediaDevice.
4. Write an interface Computer with methods powerOn() and powerOff(). Write
another interface Networkable with a method connectToNetwork(). Implement
both interfaces in a class Laptop.
Quiz
1. Which of the following is true about a class implementing multiple interfaces in Java?
A. The class must provide an implementation for all methods of all interfaces.
B. The class can implement methods from only one interface.
C. The class inherits all methods from the interfaces without the need for
implementation.
D. Interfaces can contain constructors.
Answer: A. The class must provide an implementation for all methods of all interfaces.
2. What happens if a class implements two interfaces that have a method with the same
name but different return types?
A. Compilation error.
B. The class must implement both methods with different names.
C. The class must provide only one implementation for the method.
D. The class can choose to implement one of the methods.
Answer: A. Compilation error.
3. In which version of Java were default methods introduced in interfaces?
A. Java 5
B. Java 6
C. Java 7
D. Java 8
Answer: D. Java 8
4. Given the following interfaces and class, which of the following statements is correct?
interface A {
void method();
}
interface B {
void method();
}
class C implements A, B {
@Override
public void method() {
System.out.println("Method implemented.");
}
}
A. Class C will have two method implementations.
B. Class C must provide a single implementation for method as it is declared in both
interfaces.
C. Compilation error due to method conflict.
D. Method implementations in interfaces are optional.
Answer: B. Class C must provide a single implementation for method as it is declared
in both interfaces.
5. Can an interface extend multiple interfaces?
A. No, an interface can only extend one interface.
B. Yes, an interface can extend multiple interfaces.
C. Yes, but only if the extending interface is abstract.
D. No, because interfaces cannot extend other interfaces.
Answer: B. Yes, an interface can extend multiple interfaces.
5. Nested Interfaces
Nested Interfaces in Java
Introduction
In Java, an interface can be declared inside another interface or class, forming what is known
as a nested interface. Nested interfaces allow logical grouping of interfaces and enhance the
organization of your code, especially when interfaces are only applicable within the context of a
particular class or interface. A nested interface can be both public or private depending on its
use case.
Nested interfaces are primarily used to define a contract for internal communication between
nested classes and their outer class.
Syntax for Nested Interfaces
Nested interfaces are declared like regular interfaces but inside another class or interface.
Here’s the syntax for both scenarios:
Declaring Nested Interface Inside a Class:
class OuterClass {
// Nested Interface
interface NestedInterface {
void method();
}
}
Declaring Nested Interface Inside an Interface:
interface OuterInterface {
// Nested Interface
interface InnerInterface {
void method();
}
}
Example: Nested Interface Inside a Class
Below is an example of a nested interface declared within a class and how it is implemented by
another class:
// Outer Class containing a Nested Interface
class Computer {
// Nested Interface
public interface USB {
void connect();
}
}
// Implementing the nested interface
class Keyboard implements Computer.USB {
@Override
public void connect() {
System.out.println("Keyboard connected via USB.");
}
}
public class Main {
public static void main(String[] args) {
Computer.USB keyboard = new Keyboard();
keyboard.connect();
}
}
Output:
Keyboard connected via USB.
Explanation:
- USB is the nested interface inside the Computer class.
- The Keyboard class implements the USB interface, and in the main method, we
instantiate and use the Keyboard object via the Computer.USB reference.
Example: Nested Interface Inside an Interface
Here’s an example of a nested interface inside another interface:
// Outer Interface containing a Nested Interface
interface Vehicle {
// Nested Interface
interface Engine {
void start();
}
}
// Class implementing the nested interface
class Car implements Vehicle.Engine {
@Override
public void start() {
System.out.println("Car engine started.");
}
}
public class Main {
public static void main(String[] args) {
Vehicle.Engine car = new Car();
car.start();
}
}
Output:
Car engine started.
Explanation:
● The Engine interface is nested inside the Vehicle interface.
● The Car class implements the Vehicle.Engine nested interface.
● The main method demonstrates the instantiation and usage of the Car class via the
Vehicle.Engine reference.
Advantages of Nested Interfaces
● Encapsulation: Nested interfaces can be used to tightly couple the functionality with the
outer class or interface, making the code more encapsulated.
● Logical Grouping: You can logically group the interfaces that are related only to the
outer class or interface, improving code organization.
● Readability: Nested interfaces within a class or interface make it clear that the interface
is specifically tied to the outer type.
Practice Program: Nested Interface Inside a Class
class Mobile {
// Nested Interface
public interface Charger {
void charge();
}
}
// Implementing the nested interface
class FastCharger implements Mobile.Charger {
@Override
public void charge() {
System.out.println("Mobile is charging with fast charger.");
}
}
public class NestedInterfaceDemo {
public static void main(String[] args) {
Mobile.Charger charger = new FastCharger();
charger.charge();
}
}
Expected Output:
Mobile is charging with fast charger.
Do It Yourself
1. Create a SmartHome interface with a nested DeviceControl interface. Implement
classes like Light and Fan that control devices using turnOn() and turnOff()
methods.
2. Design an Employee interface that contains a nested Department interface.
Implement the Department interface in classes like HRDepartment and
FinanceDepartment, and show how an employee belongs to a specific department.
3. Develop a Game interface with a nested Player interface, containing methods like
attack() and defend(). Implement Player in classes like Knight and Archer with
unique behaviors for each action.
4. Create a Shopping interface with a nested Payment interface. Implement payment
methods like CreditCard and PayPal, each using methods from the Payment
interface.
5. Create a University interface with a nested Course interface. Implement different
courses like MathCourse and HistoryCourse and print course details for each one.
Quiz
1. Which of the following is true about nested interfaces?
a) A nested interface cannot be declared inside a class.
b) A nested interface must be private.
c) A nested interface can only be declared inside another interface.
d) A nested interface can be declared inside both classes and interfaces.
Answer: d) A nested interface can be declared inside both classes and interfaces.
2. How can you access a nested interface declared inside a class?
a) By using the class name followed by the interface name.
b) By using the implements keyword.
c) By creating an instance of the outer class.
d) By importing the class containing the interface.
Answer: a) By using the class name followed by the interface name.
3. Which keyword is used to implement a nested interface inside a class?
a) extend
b) implement
c) interface
d) instantiate
Answer: b) implement
4. Consider the following nested interface:
class A {
interface B {
void display();
}
}
How will you implement the display() method in another class?
a) class C implements A.B { public void display() { /* code */ } }
b) class C extends A.B { public void display() { /* code */ } }
c) class C inherits A.B { public void display() { /* code */ } }
d) class C calls A.B { public void display() { /* code / } }
Answer: a) class C implements A.B { public void display() { / code */ } }
5. In which version of Java was support for private methods in interfaces introduced?
a) Java 7
b) Java 8
c) Java 9
d) Java 11
Answer: c) Java 9
References
End of Session - 19