One frequently asked Core Java interview question is: “What is the difference between abstract class and interface in Java, and when would you use each in your code?

1 Answers
Answered by suresh

Core Java Interview Question: Difference Between Abstract Class and Interface in Java

One frequently asked Core Java interview question is: "What is the difference between abstract class and interface in Java, and when would you use each in your code?"

Key Differences:

  • Focus Keyword: Abstract Class vs Interface
  • Abstract Class:
    • Contains both abstract and non-abstract methods
    • Can have method implementations
    • Can have member variables
    • Supports single class inheritance
  • Interface:
    • Contains only abstract methods
    • Cannot have method implementations
    • Cannot have member variables (prior to Java 8)
    • Supports multiple interface inheritance

When to Use Each:

  • Use an abstract class when you want to provide a common base implementation for multiple subclasses and when you have shared code among different classes.
  • Use an interface when you want to specify a set of methods that a class must implement without providing any implementation and when you want to achieve multiple inheritance in Java through interfaces.

Understanding the differences between abstract classes and interfaces is crucial for object-oriented programming in Java and enables developers to design efficient and maintainable code.

Answer for Question: One frequently asked Core Java interview question is: “What is the difference between abstract class and interface in Java, and when would you use each in your code?