Home > Java > javaTutorial > Abstraction: Abstract Class vs Interface

Abstraction: Abstract Class vs Interface

Patricia Arquette
Release: 2024-11-03 16:43:02
Original
324 people have browsed it

Abstraction: Abstract Class vs Interface

When designing software in Java, choosing between abstract classes and interfaces can have a big impact on flexibility, maintainability, and readability. In this post, we’ll explore their key differences, when to use one over the other, and look at practical examples to help you master this concept.


Key Differences Between Abstract Class and Interface

Feature Abstract Class Interface
Feature Abstract Class Interface
Purpose Achieves partial implementation Achieves complete abstraction
Method Implementations Can have both abstract and concrete methods All methods are abstract (except default/static methods in Java 8 )
Multiple Inheritance A class can extend only one abstract class A class can implement multiple interfaces
Fields/Variables Can have instance variables of any type All variables are implicitly public, static, and final
Constructors Can have constructors Cannot have constructors
Inheritance Support Can implement multiple interfaces Cannot extend an abstract class
Use Case Useful for sharing common code and state Useful for defining a contract across unrelated classes
Purpose
Achieves partial implementation Achieves complete abstraction
Method Implementations Can have both abstract and concrete methods All methods are abstract (except default/static methods in Java 8 )
Multiple Inheritance A class can extend only one abstract class A class can implement multiple interfaces
Fields/Variables Can have instance variables of any type All variables are implicitly public, static, and final
Constructors Can have constructors Cannot have constructors
Inheritance Support Can implement multiple interfaces Cannot extend an abstract class
Use Case Useful for sharing common code and state Useful for defining a contract across unrelated classes

When to Use Abstract Class vs Interface?

Use Abstract Class When:

  • You need to share state or behavior across related classes.

    Example: Employee can have fields like name and id with a common getDetails() method, shared among its subclasses Manager and Lead.

    abstract class Employee {
        String name;
        int id;
    
        Employee(String name, int id) {
            this.name = name;
            this.id = id;
        }
    
        // Concrete method shared among subclasses
        public void getDetails() {
            System.out.println(name + " (ID: " + id + ")");
        }
    
        // Abstract method to be implemented by subclasses
        abstract double getSalary();
    }
    
    class Manager extends Employee {
        Manager(String name, int id) {
            super(name, id);
        }
    
        @Override
        double getSalary() {
            return 75000;
        }
    }
    
    Copy after login
  • You want to define fields and constructors that subclasses can use.

  • You need to provide partial implementations or utility methods for subclasses.

Use Interface When:

  • You want to define a common behavior across unrelated classes.

    Example: Both Car and Drone could implement an Operable interface, as they both share a start() method but are unrelated classes.

    interface Operable {
        void start();
        void stop();
    }
    
    class Car implements Operable {
        @Override
        public void start() {
            System.out.println("Car started.");
        }
    
        @Override
        public void stop() {
            System.out.println("Car stopped.");
        }
    }
    
    class Drone implements Operable {
        @Override
        public void start() {
            System.out.println("Drone started.");
        }
    
        @Override
        public void stop() {
            System.out.println("Drone stopped.");
        }
    }
    
    Copy after login
  • You need multiple inheritance to combine different behaviors. For example, a class can implement both Runnable and Serializable.

  • You want to define default methods to add new functionality without breaking backward compatibility.


Interview Insights

Common Interview Questions:

  1. Why Can’t an Interface Have Constructors?

    Since interfaces define pure abstractions, there’s no need for constructors. Only abstract classes, which contain some implementation, require constructors to initialize state.

  2. Why Use Abstract Classes Instead of Interfaces?

    Use abstract classes when:

    • You need to share code among related classes.
    • You want to define state (fields) and constructors.
  3. Can an Abstract Class Implement an Interface?

    Yes! Abstract classes can implement one or more interfaces. They can even provide default implementations for the interface methods.

  4. Can You Use Both Abstract Classes and Interfaces in the Same Class?

    Yes, a class can extend an abstract class and implement multiple interfaces. This allows for flexible design patterns and multiple inheritance.


Summary

  • Abstract classes are ideal when you need partial implementation and shared state across related classes. They allow for common fields, constructors, and utility methods.
  • Interfaces are best suited for complete abstraction, multiple inheritance, and defining common behavior for unrelated classes. They allow you to evolve your codebase with default methods while maintaining backward compatibility.

By mastering the differences and knowing when to use each, you’ll be better equipped to design scalable, maintainable software systems.


Related Posts

  • Java Fundamentals

  • Array Interview Essentials

  • Java Memory Essentials

  • Java Keywords Essentials

  • Collections Framework Essentials

Happy Coding!

The above is the detailed content of Abstraction: Abstract Class vs Interface. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template