Java interface introduction

Java interface introduction

Interface (Interface), an abstract type in the Java programming language, is a collection of abstract methods. Interfaces are usually declared with the interface keyword. The Java interface is used to describe the collection of methods that a class has, but does not provide the code to implement these methods. They are used to define a protocol or contract (Contract), so that various implementations can follow the same interface rules for development.

Interfaces can include constants, method signatures, and default methods. Constants are implicitly declared as public static final in interfaces, while method signatures are public abstract. The default method refers to a method added after Java 8, which allows the default implementation method to be provided in the interface without requiring the implementation class to override the method.

The implementing class must implement the interface through the implements keyword and must implement all the methods declared in the interface. Since Java does not support multiple inheritance, interfaces provide a mechanism to achieve features similar to multiple inheritance. At the same time, interfaces can also be used to implement callback functions and pass messages between classes.

[In computer programming, a contract is a specification or agreement that defines how components in a program interact. Think of a contract as an agreement that individual components must abide by in order to be able to interact with other components.

Java interface and class are two different concepts, they have some similarities and some important differences.

Same point :

Both are grammatical structures in Java;

Both methods and constants can be defined;

can be inherited.

Differences :

A class can provide a specific implementation of a method, while an interface can only define the signature of a method, but cannot provide a specific implementation;

A class can implement multiple interfaces, but can only inherit from one parent class;

The variables in the interface are implicitly of public static final type, and must be initialized and assigned, while the variables in the class are not required;

The method in the interface defaults to the public abstract type and cannot have a specific implementation; while in the class, methods of public, protected, and private types can be defined and can have specific implementations;

Interfaces can also define default methods and static methods, which are added after Java 8 to provide functions such as default implementations and static methods.

[ In Java, the signature of a method (Signature) includes the method name and parameter list. The method name is used to identify the name of the method, and the parameter list describes the type and quantity of parameters that the method needs to receive, which is used to uniquely identify a method. The method signature does not contain the method return type and modifiers.

For example, the signatures of the following two methods are different:

java

public void print(String message) {}

public void print(int message) {}

Although they both have the same method name print, but their parameter list is different, one accepts a string parameter, one accepts an integer parameter, so they have different method signatures.

The composition of Java interface

The composition of the Java interface program usually includes the following parts:

Interface definition: use the interface keyword to define an interface, which contains elements such as method signatures and constants;

Implementation class definition: the implementation class implements the interface through the implements keyword, and provides specific implementation code;

Caller code: The caller can directly use the interface type to refer to any implementation class object, and call the method defined in the interface.

The following is an example that defines the interface, implementation class, and call test class in the same Java file:

//接口Animal
interface Animal {
    void eat();
}

//实现类Cat
class Cat implements Animal {
    public void eat() {
        System.out.println("Cat is eating.");
    }
}

//调用者(测试类)代码
public class Main {
    public static void main(String[] args) {
        Animal animal = new Cat();
        animal.eat(); // 打印输出:Cat is eating.
    }
}

[In the same Java file, there can only be one public class (or interface), and the name of this class must be the same as the file name.

The above example defines the interface, implementation class, and call test class in the same Java file, but it is generally not recommended, because it will reduce the readability of the code and increase the difficulty of code maintenance. We should still place the interface, implementation class, and caller test code class in separate Java files.

This storage method conforms to Java's modular design idea, which is conducive to the organization and management of codes. At the same time, this is also a requirement required by the Java compiler. If the file is not saved in this way, a compilation error will result.

It should be noted that when there are fewer implementation classes, it can also be saved in the same .java file as the interface definition. This practice, while less standardized, can improve code readability and convenience in some cases. However, the caller code should still be placed in a separate .java file to ensure program maintainability and extensibility.

The following is a simple example that demonstrates the basic structure of a program using an interface in Java:

This example consists of three files

Shape.java file:

// 定义接口
public interface Shape{
    public double getArea();
}

 Circle.java file:

// 实现Circle类
public class Circle implements Shape{
    private double radius;

    public Circle(double r){
        radius = r;
    }

    // 实现接口的方法
    public double getArea(){
        return Math.PI * radius * radius;
    }
}
// 调用者代码
public class Test{
    public static void main(String[] args){
        Shape s = new Circle(2.0);
        double area = s.getArea();
        System.out.println("圆面积:" + area); //圆面积:12.566370614359172
    }
}

In the above example, we first define a Shape interface, which contains a getArea() method to calculate the area of ​​the shape. We then define the Circle class, which implements the Shape interface and provides its own getArea() implementation. Finally, we create a Circle instance in the Test class, assign it to a Shape type variable s, and then call the getArea() method of s to calculate the area of ​​the circle.

This example shows the basic structure of Java using the interface program, which includes three parts: interface definition, implementation class definition and caller code. By using the interface, we can easily manage and extend different implementation classes, and ensure the stability and maintainability of the program.

The following is an improvement to the above example, adding the Rectangle part and modifying Test.

This example is an improvement on the previous example, adding a Rectangle file and modifying the Test file, which consists of four files:

The Shape.java file that defines the interface and the file that implements the Circle class are the same as before.

Rectangle.java class file: 

// 实现 Rectangle类
public class Rectangle implements Shape{
    private double width;
    private double height;

    public Rectangle(double w, double h){
        width = w;
        height = h;
    }

    // 实现接口的方法
    public double getArea(){
        return width * height;
    }
}

The Test.java file is modified to:

// 调用者代码
public class Test{
    public static void main(String[] args){
        Shape s1 = new Circle(2.0);
        Shape s2 = new Rectangle(3.0, 4.0);

        System.out.println("圆面积:" + s1.getArea()); //圆面积:12.566370614359172
        System.out.println("矩形面积:" + s2.getArea()); //矩形面积:12.0    }
}

interface inheritance

In Java, interfaces can inherit other interfaces just like classes, this mechanism is called inheritance of interfaces. The basic syntax of interface inheritance is as follows:

public interface SubInterface extends SuperInterface {

    // method defined by the subinterface

}

Among them, SubInterface is a subinterface, and SuperInterface is a parent interface. A sub-interface can inherit one or more parent interfaces, and multiple parent interfaces are separated by commas.

A subinterface inherits all abstract methods from its parent interface and can add new abstract methods to itself. Subinterfaces can also override the default methods and static methods in the parent interface, and the super keyword can be used to call the default method in the parent interface.

For example, the following is an example of interface inheritance:

Animal.java file:

// Animal接口
public interface Animal {
    void eat();
}

Cat.java file:

//Cat接口继承了Animal接口
public interface Cat extends Animal {
    void meow();
}

PersianCat.java file:

public class PersianCat implements Cat {
    public void eat() {
        System.out.println("The cat is eating...");
    }

    public void meow() {
        System.out.println("Meow~");
    }
}

TestA.java file:

// 调用者(测试)代码
public class TestA{
    public static void main(String[] args){
        PersianCat cat = new PersianCat();
        cat.eat(); // The cat is eating...
        cat.meow(); // Meow~
    }
}

In the above example, the Animal interface defines the eat() method, the Cat interface inherits the Animal interface and adds the meow() method, the PersianCat class implements the Cat interface, and must implement the abstract methods eat() and The newly added abstract method meow().

Similarities and differences between interface ( interface ) and abstract class ( abstract class )

[For abstract classes, please refer to https://mp.csdn.net/mp_blog/creation/editor/130618011 ]

Both interfaces and abstract classes are mechanisms used in Java to achieve polymorphism. They can both be inherited, and both can contain abstract methods, but there are many differences between them. Let's take a look at the similarities and differences between them.

1. An abstract class can contain non-abstract methods and member variables, while an interface can only contain constants and abstract methods. In other words, abstract classes can contain both concrete implementations and abstract behaviors, while interfaces can only define abstract behaviors.

2. Subclasses can only inherit one abstract class, but can implement multiple interfaces. This is because the Java language itself does not support multiple inheritance, but subclasses can achieve multiple behaviors by implementing multiple interfaces. If a class not only inherits other classes, but also implements multiple interfaces, then an abstract class must be used as the base class.

3. Abstract classes can contain construction methods, while interfaces cannot contain construction methods. This is because an interface has no concept of instantiation, so it has no need for a constructor.

4. The access rights of abstract classes can be public, protected or default, while the access rights of interfaces must be public. This is because an interface is a public contract that any class can implement, so it must be public.

5. Abstract classes can be used to define template methods, while interfaces cannot. The template method is a design pattern that defines the framework of an algorithm in an abstract class, and then implements specific steps by subclasses.

In general, we can understand the difference between an interface and an abstract class in this way: an abstract class is an abstraction of things, including both behavior and state; an interface is an abstraction of behavior, which only defines behavior specifications and has no representation of state.

When using, we should choose to use interfaces or abstract classes according to specific needs. If we need to define some basic behaviors and attributes, and want subclasses to share these basic functions, then we can use abstract classes; if we need to define some behavior specifications, but don't care about implementation details, then we can use interfaces.

Appendix , further study and understanding

Detailed Explanation of Java Interface - Alibaba Cloud Developer Community

Detailed Explanation of Java Interface - Tencent Cloud Developer Community - Tencent Cloud

Guess you like

Origin blog.csdn.net/cnds123/article/details/130618885