0% found this document useful (0 votes)
0 views28 pages

Object-Oriented Programming – Interfaces

The document explains interfaces in Java, which are contracts that classes must follow by implementing method signatures without providing their bodies. It highlights key features, differences between interfaces and abstract classes, and the benefits of using interfaces such as abstraction, loose coupling, and polymorphism. Additionally, it covers real-world examples, the Comparable and Cloneable interfaces, and the process of implementing multiple interfaces in a class.

Uploaded by

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

Object-Oriented Programming – Interfaces

The document explains interfaces in Java, which are contracts that classes must follow by implementing method signatures without providing their bodies. It highlights key features, differences between interfaces and abstract classes, and the benefits of using interfaces such as abstraction, loose coupling, and polymorphism. Additionally, it covers real-world examples, the Comparable and Cloneable interfaces, and the process of implementing multiple interfaces in a class.

Uploaded by

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

Object-Oriented Programming –

Interfaces
Understanding Interfaces in Java
What is an Interface?
• An interface is a contract that a class agrees to
follow.It contains method signatures without
implementations.The class that implements
the interface must provide implementation for
all its methods.
interface Animal {
void makeSound(); // abstract method
}
Key Features of Interfaces
• All methods are public and abstract by default.
• Interfaces support multiple inheritance.
• A class uses the implements keyword to
inherit from an interface.
• Variables in interfaces are public static final by
default.
Example
interface Animal {
void makeSound(); // Abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.makeSound(); // Output: Bark
}
}
Why Use Interfaces?
• Achieve abstraction without using abstract
classes.
• Promote loose coupling.
• Support polymorphism.
• Allow multiple inheritance in Java.
Interface vs Abstract Class
Feature Interface Abstract Class

Purpose Defines a contract for what a class Provides partial abstraction and
can do, without saying how allows defining default behavior
Purpose interface, implements abstract, extends

Keywords Used interface, implements abstract, extends

Inheritance Supports multiple inheritance (a Single inheritance only


Support class can implement multiple
interfaces)
Use Case Used when unrelated classes need Used when classes share a
to implement the same behavior common base and some
(e.g., Flyable, Drivable) default functionality
Method Types Only abstract methods (Java 7)- Can have abstract and concrete
Default and static methods (Java 8+) (non-abstract) methods
Example Use Comparable, Runnable, Cloneable Shape, Employee, Animal (with
shared behavior)
Real-World Examples of Interfaces
Interface Real-world Analogy Example in Code

RemoteControl TV remote – all remotes TV, AC implement


have buttons, but RemoteControl
implementation may vary

Driveable Anything that can be Car, Bike implement


driven – cars, bikes, trucks Driveable
Real-World Examples of Interfaces
interface Driveable {
void drive();
}

class Car implements Driveable {


public void drive() {
System.out.println("Car is driving");
}
}
Polymorphism Using Interfaces
interface Shape {
void draw();
}

class Circle implements Shape {


public void draw() {
System.out.println("Drawing Circle");
}
} public class Main {
public static void main(String[] args) {
class Square implements Shape { Shape s1 = new Circle();
public void draw() { Shape s2 = new Square();
System.out.println("Drawing Square"); s1.draw(); // Drawing Circle
}
s2.draw(); // Drawing Square
}
}
}
Multiple Interface Implementation
• In Java, a class can implement multiple interfaces. This
allows a class to inherit the behavior of multiple abstract
types, supporting a form of multiple inheritance — but
only for method signatures, not method bodies.
When we say:
• "but only for method signatures, not method bodies"

• It means that in Java interfaces, you can declare what a


method should look like (its name, return type, and
parameters) — but you cannot define what the method
actually does (its body) — unless it's a default or static
method (Java 8+).
Method Signature vs Method Body
Method Signature (Allowed in Interface)
interface Printable {
void print(); // ← This is a method signature
(no body)
}
Tells the class: “You must implement this
method.”

No code logic is written here — it's just a


contract.
Method Signature vs Method Body
Method Body (NOT allowed in traditional
interface methods)
interface Printable {
void print() {
System.out.println("Printing..."); // ❌ Not
allowed in abstract methods
}
}
Exception – default and static methods
(Java 8+)
• Java 8 introduced default and static methods in
interfaces which can have method bodies:
interface Printable {
default void print() {
System.out.println("Default Printing...");
}
}default methods provide optional implementations.

The implementing class can override them if needed.


Multiple Interface Implementation?Why is
it Useful?
• Promotes modularity.

• Enables code reuse without the complexities


of multiple class inheritance.

• Helps implement cross-cutting concerns (like


logging, data handling, or event listening).
Syntax Example(Multiple Interface Implementation)
interface Printable {
void print();
}

interface Showable {
void show();
}
class Document implements Printable, Showable {
public void print() {
System.out.println("Printing Document");
}

public void show() {


System.out.println("Showing Document");
}
}
Comparable Interface
• he Comparable interface is used to define the
natural ordering of objects of a class. It
belongs to the java.lang package.

• It allows a class to compare its objects with


each other — mainly for sorting.
Comparable Interface
• It has one method:
public int compareTo(T o);

• The interface is generic, so you specify the


type:
class Student implementsComparable<Student>
Purpose
Used when you want to:

• Sort objects of a class using natural order (e.g.,


by name, ID, marks).

• Work with classes like Collections.sort() or


Arrays.sort().
Syntax Example
class Student implements Comparable<Student> {
int id;
String name;

Student(int id, String name) {


this.id = id;
this.name = name;
}

public int compareTo(Student s) {


return this.id - s.id; // Sorts by ID in ascending order
}
}
How compareTo() Works
Return Value Meaning

0 This object is equal to the other

Positive (> 0) This object is greater

Negative (< 0) This object is less


Using with Collections
List<Student> list = new ArrayList<>();
list.add(new Student(2, "Ali"));
list.add(new Student(1, "Sara"));
list.add(new Student(3, "Ahmed"));
Collections.sort(list); // Uses compareTo()
internally
Output:Sorted by ID: 1, 2, 3
Example with Output
class Book implements Comparable<Book> {
String title;
Book(String title) {
this.title = title;
}

public int compareTo(Book b) {


return this.title.compareTo(b.title);
}
}
List<Book> books = new ArrayList<>();
books.add(new Book("Zebra"));
books.add(new Book("Apple"));
Collections.sort(books);
Output:
Apple
Zebra
Cloneable Interface?
• The Cloneable interface in Java is a marker
interface (an interface with no methods) that
is used to indicate that a class allows its
objects to be cloned — i.e., to create a copy of
an object.

• It is part of the java.lang package.


Why Use Cloneable?
• To duplicate objects without creating a new
instance manually.

• Useful when you want a copy of an object with


the same values.
Key Characteristics
Feature Description

Interface Type Marker (no methods)

Method Involved Object.clone()

Required Override protected Object clone() from java.lang.Object

Checked Exception Throws CloneNotSupportedException if not implemented


Steps to Use Cloneable
• Implement the Cloneable interface.

• Override the clone() method.

• Call super.clone() inside the overridden method.

• Handle or declare CloneNotSupportedException.


Cloning an Object(Example)
class Student implements Cloneable {
int id;
String name;

Student(int id, String name) {


this.id = id;
this.name = name; public class TestClone {
} public static void main(String[] args) throws
CloneNotSupportedException {
public Object clone() throws Student s1 = new Student(1, "Ali");
CloneNotSupportedException { Student s2 = (Student) s1.clone();
return super.clone();
} System.out.println(s1.id + " " + s1.name);
} System.out.println(s2.id + " " + s2.name);
}
}

You might also like