Why can't I use interfaces and abstract classes after reading so many source codes?

Posted by evaoparah on Wed, 09 Mar 2022 03:29:04 +0100

We may often be asked in the interview what is the interface? What is an abstract class? What is the difference between an interface and an abstract class? How should interfaces and abstract classes be used? At the same time, when we work or read the source code, we will find that interfaces and abstract classes often appear in front of us. Today, let's discuss interfaces and abstract classes.

Interface

The official interpretation of an interface is a declaration of a series of methods and a collection of method features. Then let's talk about the characteristics of the interface according to this sentence.

First of all, from the above sentence, we can see that the interface defines a series of method declarations, but there is no method implementation. From this point of view, the interface is a rule maker. It doesn't care how you implement it, only

It is a constraint that you must have these behaviors and comply with these rules. Our method needs to define a series of business logic codes to complete various specific behaviors. Therefore, the method is a form of behavior in the system, and the interface restricts what behaviors we must have. In a word, the interface is the abstraction of behavior.

For example, the company interface stipulates that people should have the behavior of working overtime (manual naughty). It's impossible not to work overtime. We can't help but advocate struggle. Then different people may complete this behavior in different ways. Some people may complete the work faster, some people may complete the work slower, some people have more tasks on hand, and some people have fewer tasks on hand. The interface abstracts the behavior and doesn't care what you do in the end, but you must have the behavior of working overtime.

Must be able to work overtime

abstract class

Abstract class is the abstraction of class intuitively, and we know that class is the abstraction of all objects belonging to the same class. Java is an object-oriented programming language, which abstracts the objective things in the real world as objects. Therefore, we know that objects are the abstraction of the objective things in the real world. In a word, abstract class is the abstraction of class and the further abstraction of objective things in the real world.

An abstract class is an abstraction of a class

Comparison between interface and abstract class

This question should be frequently asked. The author believes that we can compare the two from three angles: (1) class (2) attribute (3) method

From the perspective of class

  • To use abstract classes, a class needs to use the extends keyword, that is, it needs to inherit abstract classes. Because Java is single inheritance, it can only inherit one abstract class.
  • To use an interface, a class needs to use the implements keyword, which is called implementing the interface. At the same time, because Java is a multi implementation mechanism, multiple interfaces can be implemented.
  • Abstract classes and interfaces cannot be instantiated, that is, interfaces or abstract class objects cannot be created.

From the perspective of attributes

First, let's look at the following code

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

interface  Interface
{
    private int a=1;//may not
    int b;//may not
    int c=1;//sure
    protected int d=2;//may not;
    public int e=3;//sure
    public  static int f=4;//sure
    public static final int g=5;//sure
}

From the above code, we can see

  • There is no difference between defining attributes in an abstract class and defining attributes in an ordinary class. The attributes of an abstract class can be defined according to how they are defined.
  • In the interface, we can only use the modifiers without any modifiers, public, static and final. In fact, after decompiling, we can see that all the attributes in the interface are decorated with public static final. In other words, the attributes defined in the interface exist in the form of constants.

From the perspective of method

From the perspective of method, we should abstract the biggest difference between class and interface. Especially now, various versions are constantly changing the methods in the interface. Here, take jdk1 8 as an example, compare the differences between the methods in the interface and the abstract class.

  • Classes with abstract methods must be abstract classes, but abstract classes do not need to be all abstract methods. They can also have ordinary methods, or even all ordinary methods (but how can there be no abstract methods, and why should they be defined as abstract classes?) For ordinary methods in abstract classes, their definitions are consistent with those in ordinary classes. Private, no modification, protected and public modification can be used. For abstract methods, private modification cannot be used (because the abstract method itself needs subclass inheritance and rewriting). Ordinary methods can use static modification, while abstract methods cannot use static modification.
  • The methods in the interface can be modified without modifiers or with public. After decompilation, it can be seen that the methods in the interface are modified with public abstract, which is similar to the properties in the interface. The difference is in jdk1 8, the interface can define static methods and default methods, and the default implementation needs to be given.

How do they work together

We learn abstract classes and interfaces in order to better use abstract classes and interfaces to serve us. There is no good or bad, strong or weak between them. If so, there is no need for one of them. What we need to learn is how to use them together. We can think about this from a large number of codes and third-party frameworks in the Java world.

From the previous discussion, we can see that an interface is a constraint on behavior. It provides a mechanism to require what behaviors different classes should have, but does not limit the specific implementation of behavior. Therefore, the abstraction level of the interface should be quite high.

The abstract class we said earlier is the abstraction of the class. The author believes that the more important purpose of its design is to reuse the code on the one hand and reduce the burden of interface implementation on the other hand. When different classes have some common behaviors and the implementation methods of such behaviors are consistent, we can make these classes derive from an abstract class to avoid that all subclasses need to implement all methods in the interface, so as to realize the reuse of code and reduce the burden of implementing the interface (there is no need to implement all interface methods).

An example

example

Now let's abstract the car in the real world and think about how the abstract class and interface can be used together through an example?

  1. First of all, the trolley should be able to drive. At the same time, it needs energy to drive the engine. It can open and close the door. In this way, we abstract the four behaviors of the car into the methods in the interface, because these methods are necessary for all cars.
interface Car
{
    //travel
    public void move();

    //Replenish energy
    public void addEnergy();

    //Open the door
    public void openTheDoor();

    //close
    public void closeTheDoor();
}
  1. In this way, when we build a small car, we must first realize these four behaviors, that is, to realize these four functions, but each small car needs to realize these functions. There are many differences between various small cars, but the realization of these basic functions is similar or the same, At that time, we thought that today's small cars can be divided into fuel vehicles and trams, so we can abstract these methods. This can reduce the burden of making cars (reduce the burden of implementing interfaces) and improve the reuse rate of code.
abstract class AbstractFuelCar implements Car
{
    public void move()
    {
        System.out.println("The tanker rushes forward!!!");
    }
    public void addEnergy()
    {
        System.out.println("come on.");
        //Call the refueling method overridden by the subclass.
        refuel();
    }
    public void openTheDoor()
    {
        System.out.println("Fuel truck door...");
    }
    public void closeTheDoor()
    {
        System.out.println("Fuel truck closes...");
    }
    public abstract void refuel();
}

abstract class AbstractEnergyCar implements Car
{
    public void move()
    {
        System.out.println("The tram rushes forward!!!");
    }
    public void addEnergy()
    {
        System.out.println("Power up...");
        //Call the refueling method overridden by the subclass.
        charge();
    }
    public void openTheDoor()
    {
        System.out.println("The tram opens...");
    }
    public void closeTheDoor()
    {
        System.out.println("The tram closes...");
    }
    public abstract void charge();
}
  1. When we build a specific car, we only need to inherit the corresponding abstract class implementation template methods and some special function methods of each car, which not only improves the code reuse, but also reduces the burden of implementing the interface.
class BMW extends AbstractFuelCar
{

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

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

class Tesla extends  AbstractEnergyCar
{

    @Override
    public void charge()
    {
        System.out.println("Tesla is charging....");
    }
    public void someOtherFunction()
    {
        System.out.println("I accelerate fast!!!");
    }
}

Therefore, the general interface is used to specify what functions and behaviors the business logic should realize, while the abstract class under the interface is mainly used for code reuse, extracting some public behaviors, reducing the burden of implementing the interface, delineating the business logic process through the template method, and reducing the implementation complexity of the subclass. As shown in the figure below:

Interface abstract class

Learning in the Java World

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

"1. StringBuilder and StringBuffer"

The inheritance structure of StringBuilder and StringBuffer is as follows:

StringBuilder and StringBuffer

Inheritance structure

"2. Collection framework in Java"

ArrayList

ArrayList

HashMap

HashMap

"3. Thread pool ThreadPoolExecutor"

"4. Third party open source framework"

BeanFactory implementation class in Spring, ApplicationContext implementation class, beanpostprocessor, PointCutAdvisor implementation in AOP, Spring JDBC, transaction management, Spring MVC, SqlSession in MyBatis, etc. there are a large number of such structures. Because their inheritance structures are generally complex, pictures are not attached here. Interested students can view Spring, MyBatis and other frameworks related source code.

Topics: Java