0% found this document useful (0 votes)
14 views

PSOOP-lab 08-interfaces in java-2024-25

The document provides an overview of Java interfaces, including concepts such as single vs multiple inheritance, interface syntax, and implementation. It explains the rules for default and static methods, polymorphism via interfaces, and the benefits of using interfaces for abstraction and code reusability. Additionally, it includes examples, common interface types from the Java Standard Library, and a problem statement for practical application.

Uploaded by

dhruvvbhalani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

PSOOP-lab 08-interfaces in java-2024-25

The document provides an overview of Java interfaces, including concepts such as single vs multiple inheritance, interface syntax, and implementation. It explains the rules for default and static methods, polymorphism via interfaces, and the benefits of using interfaces for abstraction and code reusability. Additionally, it includes examples, common interface types from the Java Standard Library, and a problem statement for practical application.

Uploaded by

dhruvvbhalani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

INTERFACES

Nikahat Mulla
2

Outline
● Single vs Multiple Inheritance
● Java Interface
● Interface Syntax
● Implementing Interfaces
● Interface Example
● Extending Interfaces
● Polymorphism via Interfaces
● Example: Polymorphism via Interfaces
3

Single vs. Multiple Inheritance


● Single Inheritance: A class can inherit from
only one superclass.
● Multiple Inheritance: Java doesn’t allow
multiple inheritance through classes.
-Supports multiple inheritance using
interfaces.
4

Interfaces
● An interface in Java is a collection of abstract methods and
constants. It defines a contract that classes must follow
without providing any implementation.

● Declared using the interface keyword.

● Methods inside an interface are implicitly public and


abstract
• Can have static and default methods (Java 8+).

● Data members inside the interfaces are implicitly public,


static and final.
5

Interface Syntax
interface MyInterface {
int count; //constant
void myMethod(); // Abstract method
default void defaultMethod() {
System.out.println("Default method");
}
static void staticMethod() {
System.out.println("Static method");
}
}
6

Implementing Interfaces
• A class implements an interface using the implements keyword.
• The class must provide implementations for all the methods of the
interface.
class MyClass implements MyInterface {
@Override
public void myMethod() {
System.out.println("My Method");
}
}

public class Main {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myMethod();//abstract method of interface
obj.defaultMethod();
MyInterface.staticMethod();//static method is
qualified by interface name
}
}
7

Multiple Inheritance Using Interfaces


interface A {
void methodA();
}
interface B {
void methodB();
}

class C implements A, B {//multiple interfaces are


implemented by separating with commas
public void methodA() {
System.out.println("Method A");
}
public void methodB() {
System.out.println("Method B");
}
}
8

Rules for Default Methods

Before Java 8, interfaces could only have abstract methods (methods without
implementation). This posed a major issue when you needed to update or
extend an existing interface without breaking the implementing classes.
1. Default methods must use the `default` keyword.
2. Default methods can be overridden in implementing classes.
3. If a class implements multiple interfaces with conflicting
default methods, it must override them.(use
InterfaceName.super.methodName() to resolve ambiguity.)
4. Default methods can call other interface methods.
9

Default Methods ambiguity example


interface A { public class Main {
default void display() { public static void
System.out.println("Display from A"); main(String[] args) {
} C obj = new C();
} obj.display(); //
Output: Display from B
interface B { }
default void display() { }
System.out.println("Display from B");
}
}

class C implements A, B {
@Override
public void display() {
A.super.display(); // Call display from interface A
B.super.display(); // Call display from interface B
System.out.println("Custom logic in C");
}
}
10

Rules for Static Methods


1. Static methods must use the `static` keyword.
2. Static methods belong to the interface and
not to the object.
3. Static methods cannot be overridden by
implementing classes.
4. Static methods can only be accessed using the
interface name.
11

Example: Polymorphism via Interfaces


interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
class Cat implements Animal {
public void sound() {
System.out.println("Meow");
}
}
Animal a = new Dog();
a.sound();
12

Example: Polymorphism via Interfaces


interface Payment {
void pay(double amount);
}
class CreditCard implements Payment {
public void pay(double amount) {
System.out.println("Paid by credit card: $" + amount);
}
}
class PayPal implements Payment {
public void pay(double amount) {
System.out.println("Paid by PayPal: $" + amount);
}
}
Payment p = new CreditCard();
p.pay(100.00);
13

Extending Interfaces
interface A {
void methodA();
}
interface B extends A {
void methodB();
}
class C implements B {
public void methodA() {
System.out.println("Method A");
}
public void methodB() {
System.out.println("Method B");
}
}
14

Why use Interfaces?


• Achieves Abstraction – Defines behavior without
implementation.
• Supports Multiple Inheritance – A class can implement
multiple interfaces.
• Promotes Loose Coupling – Reduces dependency between
components.
• Encourages Code Reusability – Multiple classes can follow
the same structure.
• Enhances Polymorphism – Enables flexible method
overriding.
• Ensures Standardization – Provides a common contract for
different classes.
• Improves Testability – Easier to test using mock
implementations.
15

Rules for interfaces in Java


• Can contain constants (static & final variables)
• Cannot have constructors
Interfaces do not have constructors because they cannot be instantiated.
• Interfaces can extend other interfaces
Example:
interface B extends A {} (inherits methods from A).
• Cannot have instance variables
• Only constants (public static final) are allowed.
Example:
interface Vehicle {
int WHEELS = 4; // public static final
void start(); // public abstract
}
class Car implements Vehicle {
public void start() {
System.out.println("Car is starting...");
}
}
16

Rules of Interfaces
interface InterfaceName {
// Constant variables (public, static, final by default)
int CONSTANT_VALUE = 100;

// Abstract methods (public and abstract by default)


void method1();
void method2(int value);
}
• Methods are implicitly public and abstract in an
interface.
• Interfaces can have static methods.
• Interfaces can have default methods (from Java 8).
• A class must implement all methods if implementing
an interface or must be declared abstract.
• A class can implement multiple interfaces.
17

Interfaces from Java Standard Library


- `Comparable` - Used for sorting objects.
- `Runnable` - Used for multi-threading.
- `Serializable` - Marks a class as serializable.
- `Cloneable` - Supports object cloning.
18

Interface for Array Sorting (Using


Comparable)
class Student implements Comparable<Student> {
int rollNo;
String name;
public int compareTo(Student s) {
return this.rollNo - s.rollNo;
}
}

Arrays.sort(students); // Sorts using compareTo()


19

Question 1
Which of the following is true about interfaces?
a) An interface can have a constructor.
b) An interface can contain instance variables.
c) A class can implement multiple interfaces.
d) An interface can be instantiated.

Answer: c) A class can implement multiple


interfaces.
20

Question 2
What happens if a class implements an interface
but does not define all its methods?
a) The class must be declared abstract.
b) The program will run but with warnings.
c) The missing methods will have default
implementations.

Answer: a) The class must be declared abstract.


21

Question 3
Which of the following features was introduced in
interfaces in Java 8?
a) Constructors in interfaces
b) Private methods in interfaces
c) Default and static methods
d) Instance variables in interfaces

Answer: c) Default and static methods.


22

Predict the output


interface A {
void show();
}
class B {
public void show() {
System.out.println("Class B");
}
}
class C extends B implements A {
}

public class Main {


public static void main(String[] args) {
A obj = new C();
obj.show();
}
}

Answer : Class B
23

Predict the output


interface Test {
void display() {
System.out.println("Hello from Interface");
}
}

class Demo implements Test {


public void display() {
System.out.println("Hello from Class");
}
}

public class Main {


public static void main(String[] args) {
Test obj = new Demo();
obj.display();
}
}
Answer : Compilation error (The method display() in the interface has a body, which is
not allowed in an interface as methods are abstract by default )
24

Problem Statement
A banking system has two interfaces SavingAccount and
CurrentAccount.
The SavingAccount account has method
getSimpleInterest() and CurrentAccont has method
getCompoudInterest(). Both these interfaces are
implemented by class Customer. Customer has data
members: account type, interest rate and balance. Add any
appropriate constructors and methods. Create a main class
which creates an array of customers. Ask the user to
choose the interest type and accordingly compute interest
and update the balance. Sort the array of customers
according to balance using Arrays.sort() by implementing
the Comparable interface.
25

Thank you

You might also like