How is an abstract class different from an interface in Java
- In Java, a class can implement multiple interfaces at the same time, but inherit from only one class.
- Abstract classes are used only when the "is a" relationship type is present. Interfaces can be implemented by classes that are not related to each other.
- An abstract class is a tool for avoiding writing repetitive code, a tool for partially implementing behavior. An interface is a means of expressing the semantics of a class, a contract that describes capabilities. All interface methods are implicitly declared as public abstract or (since Java 8) default methods with a default implementation, and fields are public static final.
- Interfaces allow you to create structures of types without hierarchy.
- Inheriting from the abstract, the class “dissolves” its own individuality. By implementing an interface, it extends its own functionality.
Abstract classes contain partial implementations that are augmented or extended in subclasses. Moreover, all subclasses are similar to each other in terms of the implementation inherited from the abstract class and differ only in terms of their own implementation of the parent's abstract methods. Therefore, abstract classes are used in the case of building a hierarchy of classes of the same type, very similar to each other. In this case, inheriting from an abstract class that implements the default behavior of an object can be useful, as it avoids writing repetitive code. In all other cases, it is better to use interfaces.
Why don't some interfaces define methods at all
These are the so-called marker interfaces. They simply indicate that the class is of a particular type. An example is the Clonable interface, which indicates that the class supports the cloning mechanism.
Why can't you declare an interface method with the final modifier
In the case of interfaces, specifying the final modifier is meaningless, since all interface methods are implicitly declared as abstract, i.e. they cannot be executed without being implemented elsewhere, and this cannot be done if the method has a final identifier.
Interface has a higher level of abstraction among a class, an abstract class, an interface.
Read also:
Comments
Post a Comment