Re learning the basics of Java -- interface | CSDN creation punch in

😋 Interface

Java interface is a declaration of a series of methods and a collection of method features. An interface has only method features and no method implementation. Therefore, these methods can be implemented by different classes in different places, and these implementations can have different behaviors (functions).

🌔 Definition of interface

Interface:

  • In JAVA programming language, it is an abstract type and a collection of abstract methods. The interface is usually declared as interface. A class inherits the abstract methods of the interface by inheriting the interface. The interface is a more thorough abstraction, and all the interfaces are abstract methods. (before JDK8), interfaces cannot create objects.

  • And in order to make up for the disadvantage that we can only inherit single in our previous inheritance, Java provides us with interfaces, which can implement multiple interfaces.

  • The interface is more like expressing a capability specification. Just like before we defined animals, animals have the behavior method of eating, while other animals that implement the animal interface class must implement the behavior method of eating. Therefore, its function mainly tells the implementation class that you need to realize the functions I have.

So what's the difference between interface and abstraction?

🌕 The difference between interface and abstraction

  • Methods in abstract classes can have method bodies, that is, they can realize the specific functions of methods, but methods in interfaces cannot.
  • Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type.
  • Interfaces cannot contain static code blocks and static methods (Methods decorated with static), while abstract classes can have static code blocks and static methods.
  • A class can only inherit one abstract class, while a class can implement multiple interfaces.

be careful:

After JDK 1.8, there can be static methods and method bodies in the interface. The interface can contain specific implementation methods. This method is called the default method, and the default method is modified with the default keyword.

Let's have a look at the specific study!

🌖 Format of interface

It is mainly modified on the class through the interface keyword to make it an interface class! All methods in the interface must declare only the method id, not the specific method body.

//Format of interface:
Modifier  interface Interface name{
    // Abstract method
    void eat();
}

If the class needs to implement the keyword implements of the interface.

Points needing attention in the implementation process:

  1. You must override all abstract methods in all interfaces implemented.
  2. If a class implements an interface but does not rewrite all the abstract methods of all interfaces, the class must also be defined as an abstract class.
//Format of implementation interface:
Modifier  class Class name implements Interface name {
    // Implement all abstract methods in the interface
    void eat(){}
}


// Multi implementation format:
Modifier  class Class name implements Interface 1,Interface 2,Interface 3...{
	// Abstract method
    void eat();
    ....
}

🌗 Main components in the interface

Before JDK8, the components in the interface include abstract methods and constants

Abstract method:

The abstract methods in the interface will be automatically decorated with public abstract by default. Programmers do not need to write by themselves!!

According to the specification: it is recommended not to write public abstract for the abstract methods in the interface in the future. Why? Because it's not necessary, it will be added by default.

package src.com.na.pojo;

/**
 * First define an interface parent class -- > animal class
 * Animals have an abstract way to eat
 */
public interface Animal {


    // After being defined as an abstract method, there is no need to implement the method entity!
    // The default modifier is public abstract, which can be ignored and not written!
//    public abstract void eat();

    // This way of writing is also acceptable. public abstract is ignored by default
    void eat();

}

Constant:

In the interface, the member variable we define will be decorated with: public static final by default.

What does this mean? The member variable defined in the interface is actually a constant, and we know that the variable modified by the final keyword cannot be modified, and the variable is also statically modified by static, which means that we can access it directly with the interface name.

When defining member variables, i.e. constants, we must give initial values.

package src.com.na.pojo;

/**
 * First define an interface parent class -- > animal class
 * Animals have an abstract way to eat
 */
public interface Animal {

    // Defining member variables is a constant
    // The default modifier is public static final, which can be ignored and not written!
//    public static final String NAME = "animal";
    String NAME = "animal";
}

Note: constant naming conventions recommend that all letters be capitalized and multiple words be underlined. ANIMAL_NAME

🌘 Interface case

Let's take athletes as an example this time. Su Shen, it's on my whim. Isn't it more than the blood from Bo people and Altman.

Define athlete interface

package src.com.na.pojo;

/**
 * Define an athlete interface class. Athletes can be divided into many types: track and field athletes, weightlifters, table tennis athletes, etc.
 * Some norms between these athletes are defined.
 */
public interface SportMan {

    // For example: athletes can exercise. Do they have corresponding events
    void project();

    // Athletes will have competition results. Let's see the results.
    void performance();

    // Athletes will take part in any competition and get any award. Which place do they rank in!
    String competition(String project);  
}

Define the subclass of track and field athletes to implement the athlete interface

package src.com.na.pojo;

/**
 * Define a track and field athlete, Su Shen yyds! 9.83s
 */
public class AthleticsMan implements SportMan{

    /*
    After implementing the interface, you must rewrite all the abstract methods inside!!!
     */
    @Override
    public void project() {
        System.out.println("Su Shen participated in the 100 meter event of the Olympic Games!!");
    }

    @Override
    public void performance() {
        System.out.println("Su Shen has made history. On behalf of Asians, he can rush to the 100m finals and step into the finals! And set an Asian Record 9.83s!!!!");
    }

    @Override
    public String competition(String project) {
        return "Su Bingtian attended"+project+"Get sixth! yyds!!!";
    }
}

Define test class:

package src.com.na;

import src.com.na.pojo.AthleticsMan;

/**
 * Test interface
 */
public class Demo {
    public static void main(String[] args) {
        AthleticsMan suBingTian = new AthleticsMan();
        suBingTian.project();
        suBingTian.performance();
        System.out.println(suBingTian.competition("100 rice"));
    }
}

result:

Su Shen participated in the 100 meter event of the Olympic Games!!
Su Shen has made history. On behalf of Asians, he can rush to the 100m finals and step into the finals! And set an Asian Record 9.83s!!!!
Su Bingtian won the sixth place in the 100 meters! yyds!!!

🌙 Relationship between interfaces

We know that there can be inheritance relationship between classes, and our interface and class are implementation relationship. What about the relationship between interfaces?

In Java, interfaces can inherit from one another: that is, an interface can inherit multiple interfaces at the same time. It is equivalent to merging the abstract methods of other interfaces with this interface in inheritance.

The code is as follows:

package src.com.na;

public class Demo2 {
}


// run interface
interface Run{
    void run();
}

interface Project{
    void Project();
}

/*
 *  Summary:
 *     There are multiple implementations between interfaces and classes.
 *     There are multiple inheritance between interfaces.
 * */
interface SportMan2 extends Run , Project {
    String competition(String project);  // Abstract methods, competitions.
}

🤽 New interface methods after JDK 8

After the start of JDK 8, the interface seems to be no longer pure!

The interface is no longer just an abstract method. The interface can also have default methods (that is, instance methods) and static methods, as well as private instance methods and private static methods

1. Contains default methods and static methods

  • Default method: use the default modifier and cannot be omitted. It can be called or overridden by subclasses.

  • Static method: it is decorated with static and can be called directly by the interface.

The code is as follows:

package src.com.na.pojo;

/**
 * The test interface can contain default methods and static methods
 */
public interface InterfaceTest {
    // Contains the default method and the default keyword
    public default void defaultMethod() {
        System.out.println("Default method");
    }

    // Contains static methods and static keywords
    public static void staticMethod() {
        System.out.println("Static method");
    }
}

2. Contains private methods and private static methods

  • Private method: private modification is used for calling the default method or static method in the interface.

  • Private static method: use private modification and static modification.

The code is as follows:

package src.com.na.pojo;

/**
 * The test interface can contain private methods and private static methods
 */
public interface InterfaceTest2 {
    // Contains private methods and private modifiers
    private void privateMethod() {
        System.out.println("Private method");
    }

    // Contains private static methods, static keywords, and private modifiers
    private static void privateStaticMethod() {
        System.out.println("Private static method");
    }
}

🤾‍♂️ Interface features:

  • The methods in the interface are all abstract methods, which will be automatically decorated with public abstract by default.
  • In the interface, member variables cannot be defined, but constants can be defined, and their values cannot be changed. public static final is used by default.
  • There is no constructor in the interface, so you can't create objects!
  • The relationship between classes and interfaces is multi implemented.
  • The relationship between interfaces is multi inheritance.
  • The interface is more of a specification.
  • Starting from JDK 8, the interface is no longer pure and supports static methods, default methods and private methods.

🌸 summary

I believe all of you have a certain understanding of the knowledge and use of interfaces in Java. Wait for more basic java learning next time!

Let's cheer together! I am not talented. If there are any omissions and mistakes, I also welcome criticism and correction in the comments of talent leaders! Of course, if this article is sure to be of little help to you, please also give some praise to the kind and lovely talent leaders 👍, Collect it and welcome your attention ❤️❤️❤️ [favorite food: canned fish] ❤️❤️❤️, Thank you. If you like canned fish, too! 💕💕💕

Learn here, today's world is closed, good night! Although this article is over, I am still there and will never end. I will try to keep writing articles. The future is long. Why should we fear that cars are far away and horses are slow!

Thank you for seeing here! May you live up to your youth and have no regrets!

Keywords: Java Back-end interface

Added by biopv on Fri, 04 Feb 2022 09:07:05 +0200