Summary sharing of interfaces and abstract classes

During interviews, I am always asked the difference between interfaces and abstract classes. I think everyone's answers may be the same from the Internet. I have seen a sentence "When your efforts are the same as others, it proves that you No effort" You will be a little deeper than others is your shining point. don't talk nonsense

  1. Abstract classes have implementations of default methods, while interfaces are completely abstract implementations of methods that do not exist.


 2. In the abstract class, the main method can be written to run, and other types of non-abstract methods, while the method in the interface defaults to public static fial and cannot write the main method.


 3. Subclasses classes use the extends keyword to inherit abstract classes. If the subclass is not an abstract class, it needs to provide the implementation of all the methods declared in the abstract class, and the subclass uses the keyword implements to implement the interface. It needs to provide implementations of all declared methods in the interface.

  4. An abstract class can inherit a class to implement multiple interfaces, and an interface implements one or more interfaces.

  5, the abstract class is faster than the interface, the interface class is slightly slower, because it takes time to find the method implemented in the class

  6. If you add a new method to an abstract class, you can provide it with a default implementation. So you don't need to change your current code. If you add methods to an interface, then you must change the class that implements the interface.

When to use abstract classes and interfaces

  • If you have some methods and want some of them to have default implementations, use abstract classes.
  • If you want to achieve multiple inheritance then you have to use interfaces. Since Java does not support multiple inheritance , subclasses cannot inherit multiple classes, but can implement multiple interfaces. So you can use interfaces to solve it.
  • If the basic functionality is constantly changing, then you need to use abstract classes. If you keep changing the basic functionality and using an interface, then you need to change all classes that implement the interface.

Reference article: http://www.importnew.com/12399.html  


Guess you like

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