“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

  • Prepare for spring recruitment or summer internship in 2022, wish you every day a hundred million points of progress! Day7
  • This article summarizes abstract and Interface in Java, which will be updated daily
  • For Redis Getting started to master, Concurrent Programming, please refer to my previous blog
  • Believe in yourself, the more live more strong, alive should be open, meet water bridge! Life, you give me pressure, I return you miracle!

1, the introduction of

Abstract and interface keywords can be seen everywhere in Java, which is one of the important pillars for the implementation of Java’s three major features: encapsulation, inheritance and polymorphism. The interface keyword is used to define interface abstractions, which are essentially used to define types and capabilities that classes have. However, beginners often make the mistake of using abstract and interface. In this article, we will discuss the use of interface and abstract classes.


It is recommended to start the article with two questions:

  1. What is the difference between abstract and interface?
  2. How to choose between abstract and interface?

2, guidelines,

When defining an interface, there are some guidelines you can use to better determine whether you should define an interface or whether there are better alternatives. (Note that the points mentioned by Samba are not absolutely correct. In the actual development process, specific analysis should be made. If there is any mistake, we can communicate with each other.)

2.1 Interfaces take precedence over abstract classes

Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java Java

HashMap inheritance architecture class diagram structure:

The top-level interface of the HashMap:

public interface Map<K,V>{}
Copy the code

Abstract class for implementing HashMap:

public abstract class AbstractMap<K,V> implements Map<K,V> {}
Copy the code

AbstractMap abstract class HashMap abstract class HashMap abstract class HashMap abstract class AbstractMap abstract class, HashMap cannot inherit from other classes. For example, HashMap needs to provide serialization and cloning functions. HashMap can implement three interface Map

, Cloneable, Serializable.
,v>

Why should HashMap inherit AbstractMap abstract classes?

This is because in the JDK source design, the MAP-structured JDK needed to provide default implementations of some methods, so the JDK authors pulled a separate abstract class to implement these methods; Although Java8 Oracle tries to provide static and normal methods in the interface, xiao ba believes that there is not enough need to define method implementations in the interface as far as possible, or even at all.

What’s the difference between abstract and interface?

The differences have narrowed since Java8, but overall the two concepts are completely different:

Abstract class abstract:

  • Both abstract methods and abstract classes must be qualified by the abstract keyword
  • A class that has abstract methods must be abstract
  • Abstract classes do not necessarily have abstract methods
  • Constructors can exist in abstract classes
  • Abstract classes can have ordinary properties, methods, static properties, and static methods
  • Methods of an abstract class must be implemented in a subclass, or the subclass must be defined as an abstract class
  • Abstract classes cannot create objects with new, because calling abstract methods is meaningless without implementation

Interface features:

  • Methods in an interface are decorated by public
  • The interface object cannot be instantiated because there are no constructors in the interface
  • The interface contains only constants. If variables are defined, public static final is added by default
  • Multiple inheritance can be implemented using interfaces
  • Interfaces only have method declarations, not method bodies (used before Java8, although I didn’t say this, but many people thought this was the wrong way to design code correctly)
  • Static methods can be declared in interfaces and must be public (the default). Static methods cannot be overridden by subclasses
  • Normal methods can be declared in an interface, which must be a default modifier
Comparative study Abstract class Interface
Multiple inheritance Not supported (can only inherit one abstract class) Support (classes can implement many interfaces)
methods Abstract classes can contain both abstract and non-abstract methods All methods in the interface are implicitly abstract (Java can define static methods)
The constructor allow Don’t allow
instantiation Cannot instantiate Cannot instantiate
Access modifier Abstract classes can use public and default. Abstract methods can be public, default, or protected. Common methods can be public, default, protected, or private The interface can be public or default. Method defaults to public;

Conclusion:

  1. In the overall abstract implementation architecture, some default implementations of methods must be provided, and abstract classes can be used (since it is highly discouraged to implement some methods directly in the interface)
  2. Use interfaces if you don’t need to provide a default implementation and you need to implement multiple inheritance functionality

2.2 Methods should not be implemented in interfaces

Interfaces are everywhere. As the top layer of class architecture, all constraints and specifications provided by interfaces directly affect the lower implementation classes. So it is not recommended in the interface implementation of specific methods, although after Java8 interface definition can provide static method and the common method, but this way has a lot of risk, unless your interface design is really perfect, perfect to be responsible for all the implementation class of said your logic would never change. Otherwise, the following classes that use this method will suffer if the interface’s implementation logic is modified.

Interfaces are therefore used to define only types and capabilities of classes as much as possible. If you must define an implementation, consider using an abstract class.


2.3 Interfaces should not be used to export constants

Because it is very convenient to define constants in the interface, some friends will use the interface directly as constants export class, such as:

/ cache key * * * * < p > * < / p > * * @ Author: Liziba * @ the Date: 2021/11/2 23:12 */ public interface CacheKey { String USER = "user"; String ORDER = "order"; String MAIL = "mail"; }Copy the code

It looks very simple and doesn’t have any problems using it. But the problem is that the interface is not designed to export constants to you. To define constants, we can use enumerations or constant classes, such as the following method:

public class CacheKey {

    public static final String USER = "user";

    public static final String ORDER = "order";

    public static final String MAIL = "mail";

}
Copy the code

The interface should not be exported as a constant, but it should not be defined as a constant in the interface. If some constants are used in the abstract type of the class, it should be considered as such. It is often better to separate out constant classes to manage these constants.