0% found this document useful (0 votes)
3 views14 pages

Interface

The document compares interfaces and abstract classes in object-oriented programming, highlighting their key features, purposes, and differences. Interfaces define a contract for classes to implement without providing implementation, while abstract classes can have both abstract and concrete methods and support single inheritance. It also discusses when to use each, the benefits of interfaces, and how Java handles multiple inheritance through interfaces.

Uploaded by

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

Interface

The document compares interfaces and abstract classes in object-oriented programming, highlighting their key features, purposes, and differences. Interfaces define a contract for classes to implement without providing implementation, while abstract classes can have both abstract and concrete methods and support single inheritance. It also discusses when to use each, the benefits of interfaces, and how Java handles multiple inheritance through interfaces.

Uploaded by

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

Interface Vs Abstract Class

Interface vs Abstract Class in Object-Oriented


Programming
Both interfaces and abstract classes are used to define a blueprint for classes
in object-oriented programming (OOP). However, they serve different purposes
and have key differences.

1. Interface
An interface is a contract that defines a set of methods that a class must
implement, but it does not provide any implementation itself (except in some
cases like default methods in Java).

Key Features of Interfaces:


 Cannot have instance variables (only constants).
 Can only contain method signatures (no implementation, except default
methods in some languages).
 A class can implement multiple interfaces (supports multiple
inheritance).
 Used when unrelated classes need to follow the same contract

Example in Java:
interface Animal {
void makeSound(); // No implementation
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}
2. Abstract Class
An abstract class is a class that can have both abstract methods (without
implementation) and concrete methods (with implementation).

It cannot be instantiated on its own.

Key Features of Abstract Classes:


 Can have instance variables.
 Can provide partial implementation of methods.
 Supports single inheritance (a class can inherit only one abstract class).
 Used when classes share common behavior but also need customization.

Example in Java:
abstract class Animal {
abstract void makeSound(); // Abstract method (must be implemented)

void sleep() { // Concrete method (has implementation)


System.out.println("Sleeping...");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Bark");
}
}

3. Key Differences:

Feature Interface Abstract Class


Only method signatures (except
Can have both abstract
Methods default methods in some
and concrete methods
languages)
Instance
Not allowed (only constants) Allowed
Variables
Constructor Not allowed Allowed
Feature Interface Abstract Class
A class can implement multiple A class can inherit only
Inheritance interfaces (multiple inheritance) one abstract class
Used for sharing
Purpose Used for defining a contract
common behavior

4. When to Use What?


 Use an Interface when:
o You need to enforce a contract across multiple unrelated classes.
o You need multiple inheritance.
o No need to share code among implementations.
 Use an Abstract Class when:
o You want to provide some default behavior but still enforce
method implementation.
o You need state (variables) and constructors.
o You expect future extensions of the class.
Interfaces in Java: Introduction, Declaration, and
Implementation
1. Introduction to Interfaces in Java
An interface in Java is a blueprint for a class that defines a set of abstract
methods (method signatures without implementation). A class that implements
an interface must provide implementations for all its methods.

Key Features of Interfaces in Java

 Interfaces allow abstraction (only method declarations, no


implementations).
 A class can implement multiple interfaces (unlike extending a single
class).
 Methods in an interface are implicitly public and abstract.
 Variables declared in an interface are public, static, and final
(constants) by default.
 From Java 8, interfaces can have default and static methods with
implementations.

2. Declaration of an Interface
In Java, an interface is declared using the interface keyword.

Example: Declaring an Interface

interface Vehicle {
void start(); // Abstract method (implicitly public and abstract)
void stop();
}

Here:

 The Vehicle interface declares two methods: start() and stop().


 Any class implementing this interface must provide implementations for
these methods.
3. Implementation of an Interface
A class implements an interface using the implements keyword. The class must
provide concrete implementations for all the methods declared in the interface.

Example: Implementing the Interface

class Car implements Vehicle {


// Implementing the start() method
public void start() {
System.out.println("Car is starting...");
}

// Implementing the stop() method


public void stop() {
System.out.println("Car is stopping...");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Vehicle myCar = new Car(); // Polymorphism: Vehicle reference, Car
object
myCar.start();
myCar.stop();
}
}

Output:
Car is starting...
Car is stopping...
Another example:
Here's a complete example that includes both the interface declaration and its
implementation:

// Interface declaration
public interface Animal {
void eat();
void sleep();
}

// Implementation of the interface


public class Dog implements Animal {
@Override
public void eat() {
System.out.println("Dog is eating");
}

@Override
public void sleep() {
System.out.println("Dog is sleeping");
}
}

// Main class to test the implementation


public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
myDog.eat();
myDog.sleep();
}
}
In the Main class, we create an instance of Dog and call its eat() and sleep()
methods, demonstrating the implementation of the Animal interface.

Why Use Interfaces Instead of Abstract Classes in Java?


Both interfaces and abstract classes are used for abstraction in Java, but
interfaces provide more flexibility in certain scenarios. Here’s why we prefer
interfaces over abstract classes in some cases:
1. Multiple Inheritance Support (A Class Can Implement Multiple
Interfaces)

In Java, multiple inheritance is not allowed with classes, but it is allowed with
interfaces.

 A class can extend only one abstract class.


 A class can implement multiple interfaces.

Why Interface?
✅ Java allows multiple interface implementations, but not multiple class
inheritance.

2. Complete Abstraction (100% Abstraction)

 Abstract classes can have both abstract and concrete (implemented)


methods.
 Interfaces (before Java 8) only had abstract methods, ensuring 100%
abstraction.

🚀 Why Interface?
✅ If you want full abstraction, use interfaces instead of abstract classes.

3. Supports Future Enhancements (Java 8 Default & Static Methods)

 Since Java 8, interfaces can have default and static methods with
implementations.
 This allows code reusability without breaking existing implementations.

🚀 Why Interface?
✅ Interfaces can evolve (add methods without affecting old implementations).

4. Better Code Maintainability & Loose Coupling

 Interfaces define only behavior, not implementation, promoting loose


coupling.
 Switching implementations is easier.
🚀 Why Interface?
✅ We can easily change implementations without modifying dependent code.

5. Used in Functional Programming (Lambda Expressions)

 Interfaces with a single abstract method are called functional


interfaces.
 They support lambda expressions, making the code concise.
 🚀 Why Interface?
✅ Supports functional programming with lambda expressions.
Multiple Interfaces in Java
In Java, a class can implement multiple interfaces to achieve multiple
inheritance, which is not possible with classes. This allows a class to inherit
behavior from multiple sources.

🔹 Why Use Multiple Interfaces?


✅ Java does not support multiple class inheritance (to avoid ambiguity
issues).
✅ Multiple interfaces allow a class to have multiple behaviors without
conflicts.
✅ Promotes loose coupling and code reusability.

🔹 Example of Multiple Interfaces


// First interface
interface Animal {
void eat();
}

// Second interface
interface Sound {
void makeSound();
}

// Class implementing multiple interfaces


class Dog implements Animal, Sound {
public void eat() {
System.out.println("Dog is eating...");
}

public void makeSound() {


System.out.println("Dog is barking...");
}
}

public class Test {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.makeSound();
}
}

🔹 Output:

Dog is eating...
Dog is barking...

🔹 Key Rules for Multiple Interfaces


✅ A class can implement multiple interfaces using implements.
✅ The class must override all abstract methods from all interfaces.
✅ If interfaces have conflicting default methods, the class must override them.

🔹 Handling Default Methods in Multiple Interfaces


Since Java 8, interfaces can have default methods. But what if two interfaces have the
same method?

Example: Resolving Method Conflict

interface A {
default void show() {
System.out.println("Interface A's show method");
}
}

interface B {
default void show() {
System.out.println("Interface B's show method");
}
}

// Class implementing both interfaces


class C implements A, B {
// Must override show() to resolve conflict
@Override
public void show() {
System.out.println("Class C's own show method");
}
}

public class Test {


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

🔹 Output:

Class C's own show method

💡 If two interfaces have the same default method, the class must override it!

🔹 When to Use Multiple Interfaces?


✅ When you need multiple behaviors in a class (e.g., a Printer can be both Scannable and
Printable).
✅ When you need loose coupling (interface-based design makes code more flexible).
✅ When you want to achieve multiple inheritance (since Java doesn’t allow multiple class
inheritance).

🔹 Conclusion
Multiple interfaces allow Java to mimic multiple inheritance, making code flexible,
reusable, and loosely coupled. 🚀
Multiple Inheritance in Java
In Java, multiple inheritance refers to a class inheriting from more than one parent. Java
does not support multiple class inheritance to avoid ambiguity, but it supports multiple
inheritance using interfaces.

🔹 Why Doesn't Java Support Multiple Class Inheritance?


In languages like C++, multiple class inheritance can create ambiguity when two parent
classes have methods with the same name.

Example: The Diamond Problem

class A {
public:
void show() { cout << "Class A" << endl; }
};

class B : public A {};


class C : public A {};

class D : public B, public C {}; // Multiple class inheritance

int main() {
D obj;
obj.show(); // Ambiguity: Which show() to call? A from B or A from C?
}

💡 Java avoids this issue by disallowing multiple class inheritance! 🚀

🔹 Multiple Inheritance with Interfaces in Java


While a class cannot extend multiple classes, it can implement multiple interfaces.

✅ Example: Multiple Interface Implementation

interface Animal {
void eat();
}

interface Sound {
void makeSound();
}
// A class implementing multiple interfaces
class Dog implements Animal, Sound {
public void eat() {
System.out.println("Dog is eating...");
}

public void makeSound() {


System.out.println("Dog is barking...");
}
}

public class Test {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.makeSound();
}
}

🔹 Output:

Dog is eating...
Dog is barking...

💡 A class can inherit multiple behaviors using interfaces without ambiguity! 🎯

🔹 Handling Method Conflicts in Multiple Interfaces


Since Java 8, interfaces can have default methods, but conflicts may arise if multiple
interfaces have methods with the same name.

Example: Resolving Method Conflict

interface A {
default void show() {
System.out.println("Interface A's show()");
}
}

interface B {
default void show() {
System.out.println("Interface B's show()");
}
}

// Class implementing both interfaces


class C implements A, B {
@Override
public void show() { // Must override to resolve conflict
System.out.println("Class C's own show() method");
}
}

public class Test {


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

🔹 Output:

Class C's own show() method

💡 If two interfaces have the same default method, the class must override it!

🔹 Key Takeaways
✅ Java does not support multiple class inheritance to avoid ambiguity.
✅ Java supports multiple inheritance using interfaces (a class can implement multiple
interfaces).
✅ If two interfaces have conflicting default methods, the class must override them.
✅ This approach provides flexibility without the complexity of multiple class
inheritance. 🚀

You might also like