This question has already been answered:
Why in the java interface if there are abstract classes? In addition to multiple inheritance, what are the main differences?
This question has already been answered:
Why in the java interface if there are abstract classes? In addition to multiple inheritance, what are the main differences?
A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .
The difference in concept.
Abstract classes help create a hierarchy with common features. What matters here is the parent-heir relationship. For example, the abstract class "bird", its heirs - specific species of birds.
When used, it does not matter to us what kind of bird it will be - we use the link with the abstract class type. And we use the methods of “shout”, “walk”, “fly”. Everything is ok, but what if not all birds can fly? For example, ostrich, penguin.
Here we can be helped by interfaces that do not care about parent-child communication, they set the rules of behavior. We can distinguish the "fly" method in the interface and implement it in those birds that can fly; however, each bird can fly only in its characteristic way. We will also be able to implement this interface with the aircraft in the future and determine its flight method.
For example, we have a group of animals, birds, cars on the island and we need to ship them to another island. In this case, it will be done by those who implement the interface with the “fly” method.
And here we get two branches of polymorphism, one sets the parent-heir relationship, the second the behavior.
Suppose there are three instances of the classes horse, car, boat. All of them can implement the "people transport" interface. And no matter how each of the objects it does. The main thing that is required to do. When it is necessary to "transport people", we can access the objects that can implement it via the interface. In addition, an interface reference pointing to an instance of a class saves it from garbage collection when there are no links to it.
Realization of modularity, weak connectivity. The difference from the abstract class - in JVM there is no multiple inheritance and a concrete class can inherit only from one abstract. But to implement interfaces - maybe as many as you like.
As far as I know, interfaces in java can contain only abstract methods and no implementation. There are no designers in them. In an abstract class, there can be 1 or more abstract methods, and it can also have methods with an implementation. In AK there is a designer.
A class can inherit many interfaces, but only one class.
I write on Scala, there are used treyt instead of interfaces. The above also applies to treitures, too, but there you can still throw a type class into it, and there may be abstract and implemented methods.
Source: https://ru.stackoverflow.com/questions/569783/
All Articles