Interface is a very important concept in object-oriented programming. According to the book, using the interface, can realize the advantages of running time polymorphism, easy maintenance, easy expansion and so on. Anyone with years of programming experience will understand what these words mean, but for a budding programmer, they make no sense at all. Today I use League of Legends as the background, a detailed analysis of the interface in object-oriented programming, and the advantages of using the interface. There are two main reasons for using Java as the demo language:

  1. Java is the most popular programming language, basic learned programming will Java language;
  2. Java is a language with good support for object-oriented features;

I still remember when I began to learn Java, I did not understand the role of interface, feel the advantages of interface redundant.

For example, if I define an interface, but I need to write the implementation method of the interface in the class that implements the interface, I might as well write the implementation method in the class directly more convenient, but also omit to define the interface

I’m sure I’m not the only one. Later, as I wrote codes and read others’ codes, I gradually began to understand the function of interface, and gradually found interface to be a very convenient and awesome thing. In the textbook, most of the examples on the web that explain interfaces use defining an Animal interface, and then Dog implements that interface, Cat implements that interface; There is also a USB port for example. Most people are still dumbstruck. Now, in a new way — league of Legends. With all this talk, let’s get down to business.

Circle two important points first:
  1. The reason why Java has interfaces is that Java does not support multiple inheritance. Using interfaces, you can indirectly implement some features of multiple inheritance. There is no such thing as an interface in C++ because C++ supports multiple inheritance
  2. In object-oriented concepts, subclasses (derived classes) can be automatically converted to parent (base class) types; That is, class A implements interface B, so instantiated objects of A can be automatically converted to type B
public class Main {
    public static void main(String[] args) {
        B a = newA(); }}interface B {}class A implements B {}Copy the code

This code is correct.


At the beginning of the demo, we define a Skill interface with four methods Q, W, E, and R, which represent the four skills of the hero. For simplicity, the passive and summoner skills are not included. Then pick a hero from each of the five positions as an example: single, wild, single, ADC and assist. On the road MY favorite is Rui Wen, play wild I play the most, tangled along while chose blind monk. I had to pick Yasso in single, Rampage Girl in ADC, and Hammerstone in support.

Code first to explain:

// Skill interface
interface Skill {
    void Q(a);

    void W(a);

    void E(a);

    void R(a);
}

// Banish Blade - Raven
class RuiWen implements Skill {

    public RuiWen(a) {
        System.out.println("The day the broken sword is rebuilt, the knight returns.");
    }

    @Override
    public void Q(a) {
        System.out.println("Dance of broken Wings.");
    }

    @Override
    public void W(a) {
        System.out.println("Shake my soul and roar.");
    }

    @Override
    public void E(a) {
        System.out.println("Keep going.");
    }

    @Override
    public void R(a) {
        System.out.println("Edge of Exile."); }}// Blind Monk - Li Qing
class LiQing implements Skill {

    public LiQing(a) {
        System.out.println("With my hands I make your dreams come true.");
    }

    @Override
    public void Q(a) {
        System.out.println("Sky Sound/Echo strike");
    }

    @Override
    public void W(a) {
        System.out.println("Golden Bell Jar/Tin Shirt");
    }

    @Override
    public void E(a) {
        System.out.println("Thunder breaks my bones.");
    }

    @Override
    public void R(a) {
        System.out.println("The Dragon wags its tail."); }}// Fast Wind sword hao - Yasuo
class YaSuo implements Skill {

    public YaSuo(a) {
        System.out.println("Death, like the wind, is always with me.");
    }

    @Override
    public void Q(a) {
        System.out.println("Cut steel flash");
    }

    @Override
    public void W(a) {
        System.out.println("Wind Barrier.");
    }

    @Override
    public void E(a) {
        System.out.println("Step before chopping");
    }

    @Override
    public void R(a) {
        System.out.println("The wind is dead."); }}// Violent girl - Jinx
class JinKeSi implements Skill {

    public JinKeSi(a) {
        System.out.println("Rules are made to be broken.");
    }

    @Override
    public void Q(a) {
        System.out.println("Gun Symphony!");
    }

    @Override
    public void W(a) {
        System.out.println("Oscillating electromagnetic waves!);
    }

    @Override
    public void E(a) {
        System.out.println("Fire Cheater grenades!");
    }

    @Override
    public void R(a) {
        System.out.println("The Ultimate Reaper!"); }}// Warden of the Horcrux - Hammer Stone
class ChuiShi implements Skill {

    public ChiShi(a) {
        System.out.println("How are we going to do this pleasurable torture?");
    }

    @Override
    public void Q(a) {
        System.out.println("Death sentence.");
    }

    @Override
    public void W(a) {
        System.out.println("The Lamp of the Soul");
    }

    @Override
    public void E(a) {
        System.out.println("Doom Pendulum");
    }

    @Override
    public void R(a) {
        System.out.println("The Dungeon of Doom."); }}Copy the code

It’s a little bit too much code, but it’s very simple, 5 classes for 5 heroes. In the constructor of each class, the hero’s lines are printed when selected in the ranking. Each class implements the Skill interface and overwrites the four QWER methods, printing the name of the hero skill in the method.

Initialize the 5 heroes in the main method and call QWER for each hero, code:

public class Main {
    public static void main(String[] args) {
        // Initialize evelven, cast skills
        Skill ruiWen = new RuiWen();
        ruiWen.Q();
        ruiWen.W();
        ruiWen.E();
        ruiWen.R();

        // Initialize Liqing and release abilities
        Skill liQing = new LiQing();
        liQing.Q();
        liQing.W();
        liQing.E();
        liQing.R();

        // Initialize yasuo and release abilities
        Skill yaSuo = new YaSuo();
        yaSuo.Q();
        yaSuo.W();
        yaSuo.E();
        yaSuo.R();

        // Initialize Jinx and release abilities
        Skill jinKeSi = new JinKeSi();
        jinKeSi.Q();
        jinKeSi.W();
        jinKeSi.E();
        jinKeSi.R();

        // Initialize the hammer stone and release the ability
        Skill chuiShi = newChuiShi(); chuiShi.Q(); chuiShi.W(); chuiShi.E(); chuiShi.R(); }}Copy the code
Note one thing:

When we instantiate the 5 heroes, all of which are Skill types, look at the result:

As you can see, these five heroes are instantiated in turn, releasing QWER’s four abilities.


Maybe some of you didn’t understand this, but what does this have to do with interfaces? What are the benefits of interfaces?

A brief analysis:
  1. The concept of an interface defines a specification. The Q, W, E, and R methods are defined in the Skill interface. These methods are common in any class that implements the Skill interface.
  2. Interfaces can be thought of as a way to implement multiple inheritance, which may be an imprudent statement. There is no mechanism for multiple inheritance in Java, which loses some flexibility. However, after removing multiple inheritance, the syntax is much simpler. For example, in C++, the concept of virtual inheritance is introduced because of multiple inheritance. Anyway, back to the point. A class that implements an interface can be considered a subclass of that interface, so when we instantiate heroes (new Ruiwen()Etc.) can be instantiated directlySkillType.

Combining these two, we can call the four methods Q, W, E, and R for each Skill type object. One might wonder if I just defined four methods Q, W, E, and R in each class. But how do you make sure you have all four methods in every class? An interface constraint guarantees that all classes that implement the interface must have these four methods.

Let’s see how interfaces can be polymorphic using the following usage:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Skill hero;
        Scanner scanner = new Scanner(System.in);
        switch (scanner.nextInt()) {
            case 1:
                hero = new RuiWen();
                break;
            case 2:
                hero = new LiQing();
                break;
            case 3:
                hero = new YaSuo();
                break;
            case 4:
                hero = new JinKeSi();
                break;
            case 5:
                hero = new ChuiShi();
                break;
            default:
                hero = newRuiWen(); } hero.Q(); hero.W(); hero.E(); hero.R(); }}Copy the code

A quick look at the code defines a variable of type Skill, hreo. Determine which hero to instantiate by entering different values. Finally, the hero’s Q, W, E, R methods are called. Let’s see, type 1 is supposed to instantiate Raven the hero

No problem, type 1 successfully instantiates raven the hero and invokes raven’s four abilities. Let’s change the input value:

This time I typed 2 to instantiate the hero li Qing and invoke her four skills.

A brief description of the advantages of using interfaces:
  1. After using the interface, we realize the runtime polymorphism, that is, the specific class of hero object, at compile time we do not know, only when the program is running, we can determine which class of hero object by the value we input.
  2. After using the interface, all classes that implement the Skill interface can be instantiated as objects of the Skill type. If this is not the case, then how many variables are defined for how many heroes (classes) there are. Now the league of Legends has 154 heroes, so we need to define 154 type variables, which is…

Conclusion:

  1. The purpose of an interface is to define a set of specifications (that is, methods) that any class that implements the interface must follow.
  2. A class that implements an interface can be considered a subclass of that interface. A subclass type can be automatically converted to a superclass type, so wherever an interface appears, it can be replaced by an object of the class that implements the interface. The most common is passing in a method that defines a variable of type interface and passes in an object that implements the interface.

Finally: the article is written after work in the middle of the night, plus their own limited ability, if there is an incorrect place in the article, welcome to discuss the comment area, improve together.