Difference between interface and abstract class

1. Differences at the grammatical level

1) An abstract class can provide the implementation details of member methods (note: it can only contain non-abstract methods), while only public abstract methods can exist in interfaces, and methods are public abstract by default. However, interfaces in java8 can have default methods;

2) Member variables in abstract classes can be of various types , while member variables in interfaces can only be of
public static final type;

3) An abstract class can have static code blocks and static methods and constructors ; interfaces cannot contain static
code blocks, static methods and constructors.

4) A class can only inherit one abstract class, but a class can implement multiple interfaces

2. Differences at the design level

1) Different levels of abstraction. An abstract class is the overall abstraction of the class, including the abstraction of properties and behavior .
An interface is just an abstraction of behavior .

2) Different across domains. The abstract class embodies an inheritance relationship , and there must be
an "is-a" relationship between the parent class and the derived class, that is, the parent class and the derived class should be essentially the same in concept . This is not the case for interfaces. It
is not required that the implementer of the interface and the interface definition are essentially the same in concept. They just
implement the contract defined by the interface. The design concept is the "has-a" relationship (with or without,
with or without ). has a relationship), subclasses that implement it may not have any relationship in common.

3) The design level is different. For an abstract class, it is designed from the bottom up , we need to
know the subclass before we can abstract the parent class, but the interface is different, it does not need to know the existence of the subclass at all, just need to define a rule. , as for what subclass, when and how to implement it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325511577&siteId=291194637