1. What is an interface

We know that an abstract class can have both ordinary and abstract methods, and that a subclass inheriting an abstract class must implement its parent class’s abstract methods.

An interface is a special kind of abstract class. What’s special about it? Special in its comparison head iron, only sells abstract methods.

Interface is like some franchise stores, you want to join, must hang my signboard, decoration style must be according to me, say no more.

2. Interface definition

An interface is a “reference data type”.

Interfaces in Java are defined using the interface keyword, for example:

[List of modifiers]interfaceThe interface name{}
Copy the code
// Define a student interface
public interface StudentService {}Copy the code

Ordinary and abstract classes can be inherited by subclasses with the keyword extends. Interfaces have no inheritance, only implementation.

An implementation implements a method declared in an interface. In other words, an interface declares only one method, and the interface’s implementation class must override that method.

Methods in an interface can only be implemented by a class, which implements the interface keyword implements (implements), for example:

// StudentService specifies the implementation class of the interface
public class StudentServiceImpl implements StudentService{}Copy the code

3. Interface usage

3.1 Variables in an interface must be initialized

Since variables in the interface are of type public static Final, final modified variables cannot be changed and must be initialized.

After modification:

// Define a student interface
public interface StudentService {
    String name ="Ha ha ha.";
    public static void main(String[] args) { System.out.println(StudentService.name); }}Copy the code

Running results:

3.2 Methods in the interface are public abstract by default and cannot be changed

That is, even if you don’t write public abstract in front of a method, the interface will add these two modifiers by default.

3.3 Interface Cannot Create objects

An interface is a special abstract class that can define only abstract methods and variables, but cannot create objects and has no constructors.

This is where you’re probably going to kick my ass, because when I talked about abstract classes, I said that abstract classes have constructors. Interface even if it’s a special abstract class it’s an abstract class. Why is there no constructor?

As I said earlier when I talked about abstract classes, the constructor of an abstract class is used to initialize properties when creating a subclass object.

The interface properties are of public static final type, are immutable, and have been initialized. Is it necessary to initialize a property using a constructor?

So the interface can’t create objects, and there are no constructors.

You might argue, “Well, when we talked about inheritance, didn’t we call the superclass constructor to create a subclass object? Without an interface constructor, an interface implementation class can’t create objects.

You can understand the implementation of an interface as an inheritance, but the implementation of an interface is not an inheritance of the parent class, only inheritance can have a subclass, and the implementation of an interface method is called an interface implementation class, so the creation of an interface implementation class does not need to use the constructor of the interface.

Implementing interfaces is mainly about implementing the methods of interface declarations. What is the core? Is polymorphism.

3.4 Interface implementation classes must implement all methods of the interface

Because an interface is a special abstract class, if a class implements the interface, all the abstract methods in that class must be implemented, for example:

public interface StudentService {
    void add(a);
    void sub(a);
    void divide(a);
}
Copy the code

// StudentService specifies the implementation class of the interface
public class StudentServiceImpl implements StudentService{
    
    @Override
    public void add(a) {
        System.out.println("add");
    }
    @Override
    public void sub(a) {
        System.out.println("sub");
    }
    @Override
    public void divide(a) {
        System.out.println("divide"); }}Copy the code

3.5 Interfaces can inherit, but interfaces cannot inherit

Interfaces inherit interfaces for the purpose of program extension, but the implementation of the interface must be implemented by the class, for example:

// The teacher interface
public interface TeacherService {
    String school = "Rebus University";
}
Copy the code
// Define a student interface
public interface StudentService extends TeacherService {

    static void main(String[] args) { System.out.println(StudentService.school); }}Copy the code

Running results:

Results analysis:

  1. Because the student interface inherits the teacher interface, the student interface also has the school attribute.
  2. Since all attributes in the interface are of type public static final, you can use theInterface name. Attribute nameTo obtain.
  3. Since all methods in the interface are public abstract by default, the main method in the above example can be stripped of public.

3.6 A class can implement multiple interfaces

In fact, multiple implementations of interfaces are equivalent to multiple inheritance, which solves the defect of single inheritance.

Implement multiple interfaces, separated by commas. Such as:

public interface TeacherService {
    String school = "Rebus University";
    void add(a);
}
Copy the code
// Define a student interface
public interface StudentService {
    void sub(a);
}
Copy the code

// StudentService specifies the implementation class of the interface
public class StudentServiceImpl implements StudentService.TeacherService{


    @Override
    public void sub(a) {}@Override
    public void add(a) {}}Copy the code

4. The difference between interfaces and abstract classes

    1. Abstract classes can contain non-abstract methods, while methods declared in interfaces are all abstract.
    1. Neither abstract classes nor interfaces can instantiate objects; the main purpose of abstract classes is to extract common code.
    1. The interface solves the single inheritance problem

5. Understand interfaces

In fact, our real life is full of examples of interfaces.

    1. Computer has USB interface, you can insert keyboard, mouse, speaker box and so on.
    1. You can charge your phone with a regular charger, a quick charge, or a power bank.
    1. Bank tellers can serve customers all over the country.

These are all examples of interfaces. What benefits can you see from the above? Scalability.

In professional terms, interface – oriented programming can reduce the coupling degree and improve the scalability of the program.

The caller of a method only calls the method of the interface. The implementer of the interface implements the methods for the interface.

Interfaces decouple the caller of a method from the implementor of a method. Isn’t that polymorphism?

6. Interface cases

  1. Creating a USB Port
/ / USB interface
public interface UsbService {

    // The device is working
    void work(a);
}
Copy the code
  1. Create a new keyboard implementation class
// Keyboard implementation class
public class KeyboardServiceImpl implements UsbService {
    public static final String NAME = "Keyboard";

    @Override
    public void work(a) {
        System.out.println("The keyboard is working."); }}Copy the code
  1. Create a new mouse implementation class
// Mouse implementation class
public class MouseServiceImpl implements UsbService {
    public static final String NAME = "Mouse";

    @Override
    public void work(a) {
        System.out.println("The mouse is working."); }}Copy the code
  1. New Computer Class
/ / computer class
public class Computer {
    // Connect external devices
    public void connect(UsbService usbService){
        if(usbService instanceof KeyboardServiceImpl){
            System.out.println("Computer is connected."+KeyboardServiceImpl.NAME);
        }
        if (usbService instanceof MouseServiceImpl){
            System.out.println("Computer is connected."+MouseServiceImpl.NAME);
        }
        // Interface oriented programming, method callers are interface orientedusbService.work(); }}Copy the code
  1. The test class
public class InterfaceTest {
    public static void main(String[] args) {
        Computer computer = new Computer();
        UsbService usbService1 = new KeyboardServiceImpl();
        computer.connect(usbService1);
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
        UsbService usbService2 = newMouseServiceImpl(); computer.connect(usbService2); }}Copy the code

Running results: