Answer the question
In order to leave comments, you need to log in
What is the difference between an abstract class and an interface?
What is the difference between an abstract class and an interface in Java? And in what situations is it better to use an abstract class, and in which - an interface?
Answer the question
In order to leave comments, you need to log in
What is the difference between an abstract class and an interface in Java?
To put it "easier than Wikipedia," the main difference between an abstract class and an interface is that interfaces can be inherited multiple times, while abstract classes can contain non-abstract things.
As for their use ... everything is much simpler here if you understand why you need an abstract class, and why you need an interface. An abstract class is used when we want a concrete implementation, but it needs to be flexible. The interface is used so that the implementation of this thing exists at all.
Interfaces are used for multiple inheritance. You can't write method implementations in an interface. With these restrictions, we eliminate one of the problems of multiple inheritance: if we inherit from 2 classes with the same method (this is possible in C ++), then by calling this method in the heir, it is not clear which implementation to use. Inheriting from several interfaces, we write an implementation specifically for our class, and this problem is eliminated.
Everything is already on Wikipedia:
An interface is simply a pure abstract class, that is, a class that does not define anything other than abstract methods.
An abstract class contains abstract methods with common functionality that will be logical for the methods of its descendants (see aside Barbara Liskow's substitution principle). The interface simply describes the possibilities.
1. Interface is the contract of the system with the external environment. More Java-specific: a contract for a class to perform certain behavior, implemented in a form resembling a fully abstract class.
Apply always. This is the main way to implement abstraction.
2. Abstract class is a template for a group of cat classes. cannot be instantiated. does not contain a complete description of the behavior (may contain partial).
Apply only in specific cases when you need some kind of state in abstraction.
Specific differences can be found here: https://ru.stackoverflow.com/a/1229336/258227
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question