What is the java interface and the example of the interface

Interfaces and examples in java

1. What is an interface?
Answer: A Java interface is a series of method declarations. It is a collection of some method characteristics. An interface has only method characteristics but no method implementation. Therefore, these methods can be implemented by different classes in different places, and these implementations can have different Behavior (function).

2. Why do I need an interface?

① The interface makes up for the shortcomings of java single inheritance (only one-to-one inheritance).

② The interface is a contract, and the contract is realized by the class. In the contract, I have written some major policies and premises, and the contracted classes can implement their own functions by analyzing specific issues.

In general, the limitation of the interface is to make the specific methods more regular and uniform so that they belong to a "big family". In actual applications, for example, if the configuration of a mobile phone is good or bad, a high-end phone may have 10 functions, and we can add functions function1 to function10. There are only 5 items for low-end devices, and you can add them as you need them. It is more flexible and uniform when choosing a configuration.

3. (Example) Simply implement the interface.

First of all, let’s get to know the English words :
implement: realize

This is the name of the created class :note

①Mydoor: The main file we are going to implement, we need to implement different types or numbers of door opening methods for this door.

②MyInterface: The interface we provide for mydoor, there is no specific method

③v1, v2, v3: are three different unlocking methods, and the specific methods are implemented

Design steps:
step1: in mydoor:

 public void 函数名(接口名 为这个接口定义一个对象) {
    
    
  对象.接口中的函数();
 
  eg:
   public void open(MyInterface ni) {
    
    
  ni.opendoor();
 }

}

tep2: In MyInterface:

创建抽象方法opendoor
public void opendoor() ;

step3: Write a specific method in the V class file:

①我们需要让v1,v2,v3去implements接口MyIterface
eg:public class ImInterfaceV1 implements MyInterface{
    
    
}

②写具体的方法
public void 接口刚定义的函数名() {
    
    
  具体方法
 }
 eg:
 public void opendoor() {
    
    
  System.out.println("人脸开锁");
 }

step4: Create and call the main function in the main file Mydoor:

public static void main(String[] args) {
    
    
  Mydoor md=new Mydoor();
  
  ImInterfaceV1 imi1=new ImInterfaceV1();
  ImInterfaceV2 imi2=new ImInterfaceV2();
  ImInterfaceV3 imi3=new ImInterfaceV3();


  md.open(imi1);
  md.open(imi2);
  md.open(imi3);

}

step5: running resultsInsert picture description here

Guess you like

Origin blog.csdn.net/Lamont_/article/details/109518423