What is the difference between an interface and abstract class?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Understanding the Difference Between an Interface and an Abstract Class

Imagine you're designing a car. You have a blueprint (abstract class) that outlines the basic structure—like having wheels, an engine, and seats. But you also have a set of rules (interface) that any car must follow, such as being able to start, stop, and accelerate. Both are essential, but they serve different purposes. Let’s dive into what interfaces and abstract classes are in programming and how they differ.

What Are Interfaces and Abstract Classes

Interface

An interface is like a contract that defines a set of methods that a class must implement, without providing the actual implementation. It ensures that different classes adhere to the same set of functionalities.

Example in Java:

public interface Vehicle { void start(); void stop(); void accelerate(); }

Any class that implements the Vehicle interface must provide concrete implementations for start(), stop(), and accelerate() methods.

Abstract Class

An abstract class is a class that cannot be instantiated on its own and may contain both abstract methods (without implementation) and concrete methods (with implementation). It serves as a base for other classes to build upon.

Example in Python:

from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def make_sound(self): pass def sleep(self): print("Sleeping...")

Here, Animal is an abstract class with an abstract method make_sound and a concrete method sleep.

Key Differences Between Interface and Abstract Class

Purpose and Usage

  • Interface: Defines a contract for what a class can do, without dictating how it should do it. Ideal for defining capabilities that can be shared across unrelated classes.

    Use Case: Creating a Flyable interface for different classes like Bird and Airplane that can fly, but have different implementations.

  • Abstract Class: Provides a common base with shared code and enforces certain methods to be implemented by subclasses. Suitable when classes share a common ancestor and some behavior.

    Use Case: An Employee abstract class that includes shared attributes like name and id, and abstract methods like calculate_salary.

Inheritance

  • Interface: Supports multiple inheritance. A class can implement multiple interfaces, allowing for more flexible designs.

    Example in Java:

    public class AmphibiousVehicle implements Vehicle, Floatable { // Implement methods from both Vehicle and Floatable interfaces }
  • Abstract Class: Does not support multiple inheritance in many languages (like Java). A class can inherit from only one abstract class.

    Example in Python:

    class Car(Vehicle, Engine): # Car can inherit from one abstract class in some languages pass

Method Implementation

  • Interface: All methods are abstract by default (except default methods in some languages like Java 8+), meaning they don’t have a body.

    Example:

    public interface Drivable { void drive(); }
  • Abstract Class: Can have both abstract methods and concrete methods with implementations.

    Example:

    class Mammal(Animal): def make_sound(self): print("Generic mammal sound") def breathe(self): print("Breathing...")

Fields and Properties

  • Interface: Typically cannot have instance variables or fields (except constants in some languages).

    Example in Java:

    public interface Constants { int MAX_SPEED = 120; }
  • Abstract Class: Can have instance variables, allowing it to maintain state.

    Example in Python:

    class Appliance(ABC): def __init__(self, brand): self.brand = brand

When to Use Each

Use Interface When:

  • You need to define a role that other classes can adopt, regardless of their place in the class hierarchy.
  • You want to achieve multiple inheritances of type.
  • You want to separate the definition of methods from their implementation.

Use Abstract Class When:

  • You want to share code among several closely related classes.
  • You expect classes to have many common methods or fields.
  • You want to provide a common base with some default behavior that subclasses can override.

Practical Examples

Interface Example

public interface Payment { void processPayment(double amount); } public class CreditCardPayment implements Payment { public void processPayment(double amount) { System.out.println("Processing credit card payment of $" + amount); } } public class PayPalPayment implements Payment { public void processPayment(double amount) { System.out.println("Processing PayPal payment of $" + amount); } }

Abstract Class Example

from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass def description(self): print("This is a shape.") class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return 3.14 * self.radius ** 2

Additional Resources

Enhance your understanding of object-oriented design and prepare for interviews with these DesignGurus.io courses:

  • Grokking the Object Oriented Design Interview here
  • Grokking the System Design Interview here
  • Grokking the Coding Interview: Patterns for Coding Questions here

Helpful Blogs

Dive deeper into software design principles by visiting DesignGurus.io's blog:

By understanding the difference between interfaces and abstract classes, you can design more robust and flexible applications. Happy coding!

TAGS
Coding Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Is ByteDance a good company to work for?
Why does OpenAI pay so much?
What is a good revision strategy for coding interview problems?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
Grokking Advanced Coding Patterns for Interviews
Master advanced coding patterns for interviews: Unlock the key to acing MAANG-level coding questions.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.