We may often be asked in an interview what is an interface? What is abstract class? What is the difference between interfaces and abstract classes? How are interfaces and abstract classes used? At the same time, we often find interfaces and abstract classes in front of us when we work or read source code. Today we are going to talk about interfaces and abstract classes.

interface

The official definition of an interface is a set of method declarations, a collection of method characteristics. Let’s talk about the characteristics of the interface.

An interface is a rule maker. It does not care how you implement it, but only constrconstrs you to have these behaviors and conform to these rules. In our method, we need to define a series of business logic codes to complete a variety of specific behaviors. Therefore, method is a form of behavior in the system, while interface constrains what behaviors we must have. In a word, interface is the abstraction of behavior.

For example, the company interface stipulates that people should have the behavior of working overtime (manual naughty), it is not possible to work overtime, the total can not not advocate struggle. So different people can through different ways to complete this behavior, some people may work done faster, some people may work slowly, some people a little more task at hand, some people a little less task at hand, the interface behavior for the abstract, don’t care what you did before, but you must be able to work overtime this kind of behavior.

An abstract class

Abstract class is intuitively the abstraction of class, and we know that class is the abstraction of all objects belonging to a class, Java is an object-oriented programming language, it abstracts the objective things in the real world into objects, so we know that the object is the abstraction of the objective things in the real world. So in a word, abstract class is the abstraction of class, is the further abstraction of the objective things in the real world.

Interface versus abstract class comparison

This question is often asked. I think we can compare the two from three perspectives :(1) class (2) attribute (3) method

From a class perspective

  • To use an abstract class, a class needs to use the extends keyword, which means it needs to inherit from an abstract class, and since Java is single-inheritance, it can inherit from only one abstract class.
  • A class implements an interface by using the implements keyword, which is called implementing the interface. Java is a multi-implementation mechanism, so you can implement multiple interfaces.
  • Neither abstract classes nor interfaces can be instantiated, that is, interfaces or abstract class objects cannot be created.

From an attribute point of view

First let’s look at the following code

abstract class AbstractClass
{
    private int a;/ / can
    int b;/ / can
    protected int c;/ / can
    public int d;/ / can
    private final int e=1;/ / can
    private static int f=2;/ / can
    private static final int g=3;/ / can
}

interface  Interface
{
    private int a=1;/ / can't
    int b;/ / can't
    int c=1;/ / can
    protected int d=2;// No;
    public int e=3;/ / can
    public  static int f=4;/ / can
    public static final int g=5;/ / can
}
Copy the code

We can see from the code above

  • Defining an attribute in an abstract class is no different from a normal class-defined attribute. The attributes of an abstract class can be defined in the same way as the attributes of the defined class.
  • We can only use public, static, and final modifiers in the interface. In fact, after decomcompiling, we can see that all properties in the interface use public static final modifiers. That is, attributes defined in an interface exist as constants.

From a methodological point of view

The method Angle should abstract the biggest difference between the class and the interface, especially now each version of the interface in the method of continuous change, here take JDK1.8 as an example, compare the interface and the method in the abstract class has what difference.

  • A class with abstract methods is always an abstract class, but an abstract class does not have to be all abstract methods. It can have ordinary methods, or even all ordinary methods. For ordinary methods in an abstract class, the definition is the same as for ordinary methods in the class. You can use private, undecorated, protected, and public. You can’t use private decorations for abstract methods (because abstract methods themselves need to be overridden by subclass inheritance). Normal methods can use static modifiers; abstract methods cannot.
  • Methods in an interface can use no modifiers, or they can use public modifiers. After decomcompiling, methods in an interface are public Abstract modifiers, similar to properties in an interface. The difference is that in JDK1.8, the interface can define static and default methods and requires a default implementation.

How do they work together

We study abstract classes and interfaces, finally all is in order to be able to better use abstract classes and interfaces for our services, both is not what is good or bad, which is better or weak, if this is the case that there’s no need for the one is, we need to learn is how to make both, we can from the Java world a lot of code with a third party framework of thinking about this.

As we saw from the previous discussion, interfaces are constraints on behavior. They provide a mechanism to dictate what behavior different classes should have, but they don’t restrict how that behavior can be implemented, so the level of abstraction of interfaces should be quite high.

And the abstract class before we said that the class abstraction, its design purpose, the author thinks more important on the one hand lies in the reuse of code, on the other hand is to reduce the burden of interface implementation. When different classes with some of these public behavior, and the implementation of a consistent, then we can make the class derived from an abstract class, avoid all subclasses need to implement all the methods of interface, thus realized the reuse of code, at the same time reduce the burden of the class implements the interface (does not need to implement all the interface methods).

A case in point

Now that we’re abstracting a car from the real world, think about how an abstract class and interface can work together as an example.

1, first of all, the car should be able to run, and at the same time need energy to drive the engine, can open the door, can close the door. In this way, we abstract the four behaviors of the small car into methods in the interface, because these methods are required of all small cars.

interface Car
{
    / / travel
    public void move(a);

    // Add energy
    public void addEnergy(a);

    / / open the door
    public void openTheDoor(a);

    / / close the door
    public void closeTheDoor(a);
}
Copy the code

2, so when we build the car, we must first realize the four behaviors, that is, to realize the four functions, but every car car needs to realize these functions, there are many differences between various cars, but these basic functions are similar or the same, At this time, we think of the current car can be divided into fuel car and trolley car, so we can abstract the realization of these methods. This can reduce the burden of building cars (reduce the burden of implementing interfaces) and increase the rate of code reuse.

abstract class AbstractFuelCar implements Car
{
    public void move(a)
    {
        System.out.println("Oil truck chug chug chug forward!!");
    }
    public void addEnergy(a)
    {
        System.out.println("Come on...");
        // Call the refueling method overridden by the subclass.
        refuel();
    }
    public void openTheDoor(a)
    {
        System.out.println("Oil truck open the door...");
    }
    public void closeTheDoor(a)
    {
        System.out.println("Close the fuel truck...");
    }
    public abstract void refuel(a);
}

abstract class AbstractEnergyCar implements Car
{
    public void move(a)
    {
        System.out.println("The tram zips forward!!");
    }
    public void addEnergy(a)
    {
        System.out.println("Power up...");
        // Call the refueling method overridden by the subclass.
        charge();
    }
    public void openTheDoor(a)
    {
        System.out.println("Tram open...");
    }
    public void closeTheDoor(a)
    {
        System.out.println("Tram closed...");
    }
    public abstract void charge(a);
}
Copy the code

3. When we build specific cars, we only need to inherit the corresponding abstract class implementation template method and some unique functional methods of each car, which not only improves code reuse, but also reduces the burden of interface implementation.

class BMW extends AbstractFuelCar
{

    @Override
    public void refuel(a)
    {
        System.out.println("BMW refuels !!!!");
    }

    public void someOtherFunction(a)
    {
        System.out.println("I'm a little expensive..."); }}class Tesla extends  AbstractEnergyCar
{

    @Override
    public void charge(a)
    {
        System.out.println("Tesla is recharged...");
    }
    public void someOtherFunction(a)
    {
        System.out.println("I speed up fast!!"); }}Copy the code

Therefore, the general interface is used to define what kind of functions and behaviors business logic should achieve, while the abstract class is mainly used for code reuse under the interface to extract some common behaviors and reduce the burden of implementing the interface. The business logic process is delineated through the template method to reduce the implementation complexity of subclasses. As shown below:

Learn in the Java world

Let’s take a look at how interfaces and abstract classes are used together in Java class libraries and some common third-party open source frameworks.

StringBuilder and StringBuffer

The inheritance structure of StringBuilder and StringBuffer is as follows:

2. Collection framework in Java

ArrayList

HashMap

ThreadPoolExecutor

4. Third-party open source framework

Spring implements BeanFactory, ApplicationContext, BeanPostProcessor,AOP PointCutAdvisor, etc., SpringJDBC, Transaction management, SpringMVC, MyBatis SqlSession has a large number of such structures, because its inheritance structure is generally more complex, here no longer attach pictures, interested students can view Spring,MyBatis and other frameworks related source code.