This is the 23rd day of my participation in the August More Text Challenge.More challenges in August

Java interfaces

preface

This section is also more abstract, now slowly understand it, to the back to do more examples will understand the truth!

Read more books, read more newspapers, eat less snacks and sleep more ~

2021/8/23, programming learning does not stop!

The target

  1. Java Interface

  2. What is an interface

  3. Why you need an interface

  4. How are interfaces defined and implemented

  5. Interface features, etc

  6. Contrast abstract classes with interfaces

1. The concept

A Java interface is a declaration of a series of methods. It is a collection of method characteristics. An interface has only the characteristics of methods but no implementation of methods.

In Java, a class decorated with the keyword interface is an interface. An interface defines a behavioral protocol that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of abstract methods, none of which has a concrete implementation. The class that implements the interface (the implementation class) must implement all the abstract methods defined in the interface.

Interfaces are not classes. Interfaces are written in much the same way as classes, but they are different concepts. Classes describe properties and methods of objects. Interfaces contain the methods that the class implements.

Unless the class implementing the interface is abstract, that class defines all methods in the interface.

Interfaces cannot be instantiated, but can be implemented. A class that implements an interface must implement all the methods described in the interface, or it must be declared abstract

2. Why do you need interfaces

We know that Java supports only single inheritance, which means that a class is allowed to have only one direct parent, thus ensuring data security. Java does not support multiple inheritance as shown below:

Interface is to solve the problem of Java single inheritance, although a class can only have a direct parent class, but it can implement multiple interfaces, no inheritance relationship of the class can also implement the same interface. The dual design of inheritance and interface not only keeps the data security of the class but also realizes multiple inheritance.

2.1 Differences between Interfaces and classes

  • Interfaces cannot be used to instantiate objects.
  • The interface has no constructor.
  • All methods in an interface must be abstract methods. After Java 8, non-abstract methods can be modified with the default keyword in an interface.
  • Interfaces cannot contain member variables, except static and final variables.
  • Interfaces are not inherited by classes; they are implemented by classes.
  • Interfaces support multiple inheritance.

2.2 Interface Features

  • Each method in the interface is also implicitly abstract. Methods in the interface are implicitly specified as public abstract (only public abstract; other modifiers will return an error).
  • An interface can contain variables, but variables in the interface are implicitly specified as public static final variables (and only public; using the private modifier raises a compilation error).
  • Methods in an interface cannot be implemented in an interface, only by the class that implements the interface.

[ImG-JYpuaqln-1629772518841] (E:\Typora\Image\image-20210823103037781.png) [jypuaqln-1629772518841]

It can be seen from IDEA that these keywords are gray, which means they are hidden and can be written or not

2.3 The difference between Abstract classes and interfaces

  • 1. Methods in an abstract class can have a method body, which implements the specific functions of the method, but not methods in an interface.
  • 2. Member variables in an abstract class can be of various types, whereas member variables in an interface can only be of public static final type.
  • 3. An interface cannot have static code blocks and static methods, whereas an abstract class can have static code blocks and static methods.
  • 4. A class can inherit only one abstract class, while a class can implement multiple interfaces.

3. Definition and implementation of interfaces

3.1 Defining Interfaces

3.1.1 Interface Declaration

Declare an interface using the interface keyword:

public interface Personal {... }Copy the code

An interface declaration requires two elements: the interface keyword and the interface name. The public modifier indicates that the interface can be used in any class of any package. If you specify an access modifier for the display, the interface can only be used by classes in the same package.

3.1.2 Interface Body

In the interface body, you can define constants and method declarations:

public interface Personal {
  	final String NAME = "I'm a constant in the Personal interface";
	void walk(a);
  	void run(a);
}
Copy the code

The Personal interface above is an interface that defines a constant NAME and two abstract methods walk() and run().

An interface is more “abstract” than an abstract class. It cannot have a concrete implementation of the methods underneath it. All methods must be abstract.

Interfaces can also contain constant declarations in addition to method declarations. All constants defined in an interface are public, static, and final by default.

Member declarations in interfaces do not allow the use of private and protected modifiers.

3.2 Interface Implementation

Interfaces define behavioral protocols that the classes that implement them follow. The implements keyword is used to implement an interface. A class implements one or more interfaces. To implement multiple interfaces, the implements keyword is followed by a comma-separated list of the interface names to be implemented by the class. The syntax is:

public class Test implements Interface1.Interface2
Copy the code

Here is sample code for the Test class that implements the Interface1 interface:

package com.caq.oop.demo11;

// Multiple inheritance, which resolves the single inheritance problem in Java (only one subclass can inherit from a parent class)
public class Test implements Interface1.Interface2 {
    @Override
    public void eat(a) {
        System.out.println("Implement the eat method in Interface1 with the Test class");
    }

    @Override
    public void eat2(a) {
        System.out.println("Implement the EAT2 method in Interface1 with the Test class");
    }

    @Override
    public void run(a) {
        System.out.println("Implement the Run method in Interface1 with the Test class");
    }

    @Override
    public void run2(a) {
        System.out.println("Implementing the Run2 method in Interface1 through the Test class");
    }

    public static void main(String[] args) {
        String name =  Interface1.NAME;
        System.out.println(name);
        Test test = newTest(); test.eat(); test.run(); }} I'm a constant in Interface1 using Test to implement eat in Interface1 using Test to implement run in Interface1Copy the code

In the above code, the Test class implements the Interface1,Interface2 interfaces. It is worth noting that interface names can be used. Call a constant declared in the interface as a constant name:

String name = Test.NAME;
Copy the code

4. Interface inheritance

Interfaces also have inheritance relationships. Interface inheritance uses the extends keyword

public interface Interface2 {
    String NAME = "I'm a constant in Interface2.";

    void eat2(a);

    void run2(a);
}
Copy the code

When a class implements an Interface2 interface, it implements all the abstract methods that the interface inherits:

public interface Interface1 extends Interface2 {
    String NAME = "I'm a constant in Interface1.";

    void eat(a);

    void run(a);

    @Override
    void eat2(a);

    @Override
    void run2(a);
}
Copy the code

It is worth noting that an interface can inherit from more than one parent interface, with the interface name placed after the extends, separated by commas, for example:

// Interface1.java
public interface Interface1 {
    void abstractMethod1(a);
}

// Interface2.java
public interface Interface2 {
    void abstractMethod2(a);
}

// Interface3.java
public interface Interface3 extends Interface1.Interface2 {
    void abstractMethod3(a);
}
Copy the code

As a bonus, when an implementation class has the extends keyword, it should be followed by the implements keyword:

public class MyClass extends SuperClass implements Interface {... }Copy the code

5. Default and static methods

Starting with JDK 1.8, default and static methods can be defined in the interface. Unlike abstract methods, implementation classes may not implement default methods and class methods.

5.1 Default Methods

5.1.1 statement

We can use the default keyword to implement methods with a method body in the interface topic, for example:

public interface Personal {
  	void run(a);
  
  	default void eat(a) {
      	System.out.println("I'm the default way to eat."); }}Copy the code

5.1.2 Call and Override

In an implementation class, you may not implement the default method:

public class Pet implements Personal {  	@Override    public void run(a) {        System.out.println("Animals can run");    }}
Copy the code

We can also override the default method in the implementation class without the default keyword:

public class Pet implements Personal {  	@Override    public void run(a) {        System.out.println("Animals can run");    }    	@override public void eat() {// Use the interface name. Super. Call the default personal.super.eat () method in the interface with the method name (); System.out.println(" Animals eat "); }}
Copy the code

If you want to call the default method of the interface in the implementation class, you can use the interface name. Super. Method name (). So the name of the interface — super is the reference to the interface.

5.1.3 Application Scenarios

When a method does not require all implementation classes to implement it, you can declare the method as the default method in the interface. Another advantage of using the default method is that when an interface adds a method, it is set as the default method and overridden only in the class that needs to implement it, rather than in all implementation classes.

5.2 Static Methods

5.2.1 statement

Declare static methods on an interface using the static keyword, for example:

public interface Personal {
    void walk(a);
    // Declare static methods
    static void sayHello(a) {
        System.out.println("Hello imooc!"); }}Copy the code

5.2.2 call

A static method in a class only

Can be inherited by subclasses and cannot be overridden, as in implementation classes, static methods cannot be overridden. If you want to call a static method in an interface, just use the interface name. Class method name can be called:

public class Pet implements Personal {
    @Override
    public void walk(a) {
      	// Call the class method in the interface
        Personal.sayHello();
        System.out.println("Animals can walk."); }}Copy the code

6. The difference between interfaces and abstract classes

  1. The default method of an interface is public, all methods can have no implementation in the interface (Java 8 interface methods can have default implementation), and abstract classes can have non-abstract methods;
  2. An interface cannot have any variable except static or final, whereas an abstract class can.
  3. A class can implement multiple interfaces, but only one abstract class. The interface itself can extend multiple interfaces with the extends keyword;
  4. The default modifier for interface methods is public, and abstract methods can have public, protected, and default modifiers. (Abstract methods cannot use the private keyword because they are intended to be overridden!) ;
  5. The main solution of the abstract class is that the subclass overrides the method of the parent class every time. The parent class does not need to write the method body, because the subclass overrides the method of the parent class every time. So adding abstract to the front of the class is a hint that the method will be overridden
  6. Interface mainly solves the defect of single inheritance in Java. From the design level, interface is an abstraction of behavior and a behavior specification, while abstract class is an abstraction of class and a template design

7. Duplicate member resolution in multiple interfaces

7.1 Default methods with The Same Name Exist on Multiple Interfaces

For example, if there are two interfaces, myInteface1.java and Interface2.java, there is a default method with the same signature:

public interface Interface1 {
    default void defaultMethod(a) {
        System.out.println("I'm the default method in Interface1."); }}public interface Interface2 {
    default void defaultMethod(a) {
        System.out.println("I'm the default method in Interface2."); }}Copy the code

The default method of the same name will conflict when the implementation class implements two interfaces. The solution is to override the default method in the implementation class:

public class MyClass implements Interface1.Interface2 {
	public void defaultMethod(a) {
      	System.out.println("I'm the default method to override."); }}Copy the code

There is also a case where the implementation class inherits a parent class with the same name as the default method, and there are three methods with the same name:

// Declare a parent class and define a method with the same name in the parent class
public class FatherClass {
  	public void defaultMethod(a) {
        System.out.println("I'm defaultMethod() method in FatherClass."); }}// The implementation class inherits the parent class and implements two interfaces
public class MyClass extends FatherClass implements Interface1.Interface2 {}Copy the code

Instantiate MyClass by calling its defaultMethod() method:

MyClass myClass = new MyClass();
myClass.defaultMethod();
Copy the code

No error will be reported when the compiler executes:

I'm the defaultMethod() method in SuperClassCopy the code

In fact, it implements defaultMethod(), which implements the class’s parent, FatherClass, without overwriting it.

7.2 Duplicate Name Constants Exist on Multiple Interfaces

For example, if two interfaces have constants with the same name:

public interface Interface1 {
    final int NUM = 100;
}

public interface Interface2 {
	final int NUM = 200;
}
Copy the code

At this point in the implementation class, we can use the interface name. Constant names are called in the same way:

public MyClass implements Interface1, Interface2 {
	  System.out.println(Interface1.NUM);  	
	  System.out.println(Interface2.NUM);  	
}
Copy the code

When an implementation class enters an inheritance relationship:

class SuperClass {
  	static int NUM = 300;
}

public MyClass extends SuperClass implements Interface1, Interface2 {	
    System.out.println(NUM);
}
Copy the code

When an attribute or constant in a parent class has the same name as a constant in an interface, a subclass cannot tell which NUM is the same name. The compiler will report an error:

System.out.println(NUM); system.out.println (NUM); ^ NUM in SuperClass and NUM in Interface1 both match 1 errorCopy the code

If NUM is declared in a subclass, it will compile:

public MyClass extends SuperClass implements Interface1, Interface2 {
  	int NUM = 3;
	System.out.println(NUM);
}
Copy the code

Nodule 8.

Through learning, we know that Java’s interface was created to solve the disadvantages of its single inheritance

You can use the interface keyword to declare an interface

There can be no specific method implementation inside the interface.

You can use the implements keyword to implement the interface

An interface can inherit from more than one parent interface, separated by commas after extends.

Starting with Java 8, default methods and static methods can be defined in interfaces.