Home >Java >javaTutorial >Java interface usage example analysis

Java interface usage example analysis

王林
王林forward
2023-04-19 08:55:041244browse

Java interface usage example analysis


Interface

One picture flow
Java interface usage example analysis

The concept of interface and summary of some knowledge points

Interface (English: Interface) is an abstract type in the JAVA programming language and is a collection of abstract methods. Interfaces usually Declare with interface. A class inherits the abstract methods of the interface by inheriting the interface.
Interfaces are not classes. The way to write interfaces is very similar to classes, but they belong to different concepts. Class describes the properties and methods of an object. The interface contains the methods to be implemented by the class.
Unless the class that implements the interface is an abstract class, otherwise the class must define all methods in the interface.
The interface cannot be instantiated, but it can be implemented. A class that implements an interface must implement all methods described in the interface, otherwise it must be declared as an abstract class . In addition, in Java, interface types can be used to declare a variable, They can become a null pointer, or be bound to an object implemented by this interface.

The similarities between interfaces and classes

    There can be multiple interfaces in one interface
  • The file is saved in a file ending with .Java. The file name uses the interface name
  • . The bytecode file of the interface is saved in a file ending with .class.
  • The bytecode file corresponding to the interface must be in the directory structure matching the package name
The difference between interface and class

    Interface cannot be used to instantiate objects
  • Interface has no constructor method
  • All methods in the interface must be abstract Methods, non-abstract methods modified with the default keyword can be used in interfaces after Java 8
  • Interfaces cannot contain member variables, except for static and final variables
  • The concept that an interface is inherited by a class is not accurate. To be precise, it should be implemented by a class.
  • Interfaces can achieve what we call multiple inheritance
Some characteristics of interfaces

    Every method in the interface is also implicitly abstract, so the methods in the interface will be implicitly designated as public abstract (It can only be public abstract, other modifiers will report an error)
  • The interface contains variables, but the variables in the interface will be implicitly designated as public static final variables (and can only It is public. Modifying it with private will report a compilation error)
  • The methods in the interface cannot be implemented in the interface. The methods in the interface can only be implemented by the class that implements the interface.
The difference between abstract classes and interfaces

Before JDK1.8, they had the following differences

    Methods in abstract classes can have specific executable statements, that is, method bodies, which can realize the specific functions of the method, but methods in interfaces cannot (for example:
  • System.out.println(“I'm super corn !!”);

    )

  • Member variables in abstract classes can be of
  • various types

    , while member variables in interfaces can only be# The ##public static final type of

    interface cannot contain static code blocks and the use of static methods (methods modified with static), while abstract classes can have static code blocks and static methods
  • A class can only inherit one abstract class, but a class can implement multiple interfaces
  • So here It should be noted that:
After JDK1.8, interfaces are allowed to contain static methods and method bodies, and are allowed to contain specific implementation methods. We call this method the "default method". This method uses the default key Words to modify


After JDK1.9, methods are allowed to be defined as private, so that some reused codes will not expose the methods
Abstract classes exist The meaning is to allow the compiler to better verify. Generally, we will not use abstract classes directly, but use its subclasses. If we accidentally create an object through an abstract class, the compiler will remind us in time.

Note: Just browse the above content roughly once. It doesn’t matter if you don’t understand it. I will explain it to you one by one below, and then you will have a better understanding of these knowledge points when you look back. The feeling of waking up from a big dream

#So in real life, what is the interface? It can be a USB port on a laptop, a power socket, etc.


Java interface usage example analysisThen these interfaces are also different in terms of implementation and usage standards
Java interface usage example analysis

The USB port of the computer can be plugged into: U disk, mouse, keyboard...all devices that comply with the USB protocol
  • The power socket jack can be plugged into: computer, TV, rice cooker...all devices that meet the specifications

Through the above examples we It can be seen that the interface is a public behavioral standard. When everyone implements it, as long as it meets the standard, it can be used universally. In Java, an interface can be seen as: a common specification for multiple classes, which is a reference data type

Grammar rules

Definition format and definition class of interface The format is basically the same. Replace the class keyword with the interface keyword to define an interface.

public interface 接口名称{
    //抽象方法
    public abstract void method1();
    //public abstract是固定搭配,可以不写
    public void method2();
    abstract void method3();
    void method4();
    
    //注意:在接口中上述的写法都是抽象方法,所以method4这样写代码更整洁}

Tips:

  1. When creating an interface, the name of the interface generally starts with the capital letter I (pronounced ai)

  2. Interfaces are generally named using words with adjective parts of speech

  3. It is agreed in the Alibaba coding standards that no modifiers should be added to the methods and properties in the interface to keep the code clean

Use of interface

The interface cannot be directly instantiated and used. There must be a class to implement it and implement all abstract methods in the interface

public class 类名称 implements 接口名称{
    //...}

Note: There is an extends inheritance relationship between the subclass and the parent class, and there is an implementation relationship between the class and the interface.

USB mouse and USB keyboard classes and interfaces are used in laptops to implement functions

  1. USB interface: includes the functions of opening and closing the device

  2. Laptop class: including the function of switching on and off and using USB devices

  3. Mouse class: implements USB interface and has click function

  4. Keyboard class: implements USB interface and has input function

##
//USB接口public interface USB{
    void openDevice();
    void closeDevice();}//鼠标类,实现USB接口public class Mouse implements USB{
    @Override
    public void openDevice(){
        System.out.println("打开鼠标");
    }
    
    @Override
    public void closeDevice(){
        System.out.println("关闭鼠标");
    }
    public void click(){
        System.out.println("鼠标点击");
    }}//键盘类,实现USB接口public class KeyBoard implements USB {
    @Override
    public void openDevice(){
        System.out.println("打开键盘");
    }
    
    @Override
    public void closeDevice(){
        System.out.println("关闭键盘");
    }
    
    public void inPut(){
        System.out.println("键盘输入");
    }}//笔记本类:使用USB设备public class Computer {
    public void powerOn(){
        System.out.println("打开笔记本电脑");
    }
    
    public void powerOff(){
        System.out.println("关闭笔记本电脑");
    }
    public void useDevice(USB usb){
        usb.openDevice();
        if(usb instanceof Mouse){
            Mouse mouse = (Mouse)usb;
            mouse.click();
        }else if(usb instanceof KeyBoard){
            KeyBoard keyBoard = (KeyBoard)usb;
            keyBoard.inPut();
        }
        usb.closeDevice();
    }}//测试类:public class TestUSB{
    public static void main(String[] args){
        Computer computer = new Computer();
        computer.powerOn();
   
    //使用鼠标设备
    computer.useDevice(new Mouse());
    
    //使用键盘设备
    computer.useDevice(new KeyBoard());
    
    computer.powerOff();
    }}
Output:


Java interface usage example analysis

instanceof

In the above code example, instanceof is mentioned. Some friends may not understand it. I introduced it in the previous blog. Here I will explain it to you again

Instanceof is a reservation of Java. Keywords, objects on the left, classes on the right, and the return type is Boolean.
Its specific function is to test whether the object on the left is an instantiated object created by the right class or a subclass of the right class
If so, it returns true, otherwise it returns false

[Note on the use of instanceof Matters】 Existing inheritance relationship, and the use of instanceof (including the implementation of the interface)

[instanceof application scenarios] Object coercion needs to be used When type conversion, you need to use instanceof to judge

Characteristics of the interface

  1. The interface type is a reference type, but you cannot directly new the object of the interface

  2. public class TestUSB {
        public static void main(String[] args){
            USB usb = new USB();
        }}//编译会出错:USB是抽象的,无法实例化

Java interface usage example analysis

  1. Every method in the interface is a public abstract method, that is, the methods in the interface will be implicitly designated as public abstract( It can only be public abstract, other modifiers will report an error)

  2. public interface USB {
        //编译出错:此处不允许使用修饰符private
        //或者是java: 缺少方法主体, 或声明抽象
        private void openDevice();
        void closeDevice();
        //不同JDK版本编译器的标准是不一样的,报错也是不一样的}
  1. The methods in the interface cannot be implemented in the interface, and can only be implemented by the class that implements the interface To achieve

  2. public interface USB {
        void openDevice();
        
        //编译失败:因为接口中的方法默认为抽象方法
        //Error:接口抽象方法不能带有主体}

Java interface usage example analysisBut if we add a default here, then the method body can be implemented.

Java interface usage example analysis

  1. When overriding a method in an interface, default cannot be used as an access permission modification

  2. public interface USB {void openDevice();//默认为publicvoid closeDevice();//默认为public}public class Mouse implements USB {
        @Override
        void openDevice(){
            System.out.println("打开鼠标");
        }
        
        //...}//这里编译会报错,重写USB中的openDevice方法时,不能使用默认修饰符

Java interface usage example analysisImplement this interface, and the access qualification modifier range of the method that overrides this interface is larger than that in the interface

  1. The interface can contain variables, but the variables in the interface will be The compiler automatically and implicitly specifies

    public static finalvariable

  2. public interface USB {
        double brand = 3.0;//默认为:final public static修饰
        void openDevice();
        void closeDevice();}public class TestUSB {
        public static void main(String[] args){
            System.out.println(USB.brand);
            //可以直接通过接口名访问,说明变量时静态的
            
            //下面写法会报错 Java:无法为最终变量brand分配值
            USB.brand = 2.0;
            //说明brand具有final属性
        }}

Java interface usage example analysis

  1. There cannot be static in the interface Code blocks and construction methods

  2. public interface USB {
        public USB(){
        
        }//编译失败
        
        {
        
        }//编译失败
        
        void openDevice();
        void closeDevice();}

Java interface usage example analysis

  1. Although the interface is not a class, it is the suffix of the bytecode file after the interface is compiled. The format is also .class

  2. If the class does not implement all abstract methods in the interface, the class must be set to an abstract class

  3. as specified in JDK8 The interface can contain the default method mentioned above


implement multiple interfaces

In Java, there is single inheritance between classes, one A class can only have one parent class, that is,

multiple inheritance is not supported in Java, but a class can implement multiple interfaces. The following code is used to demonstrate

public class Animal {
    protected String name;
    
    public Animal(String name){
        this.name = name;
    }}

Then we write a set of interfaces to represent "things that can fly", "things that can run" and "things that can swim".

public interface IFlying {
    void fly();}public interface IRunning {
    void run();}public interface ISwimming {
    void swim();}

Java interface usage example analysis
那么接下来我们创建几个具体的动物类来接受并实现这些接口
比如,猫会跑

public class Cat extends Animal implements IRunning{
    public Cat(String name) {
        super(name);
    }
    
    @Override
    public void run() {
        System.out.println("小猫"+this.name+"正在跑");
    }}

鱼会游泳

public class Fish extends Animal implements ISwimming{
    public Fish(String name){
     super(name);   
    }
    
    @Override
    public void swim() {
        System.out.println("小鱼"+this.name+"正在游泳");
    }}

而青蛙即会跑又会游泳

public class Frog extends Animal implements IRunning,ISwimming{
    public Frog(String name){
        super(name);
    }
    
    @Override
    public void run() {
        System.out.println("青蛙"+this.name+"正在跑");
    }

    @Override
    public void swim() {
        System.out.println("青蛙"+this.name+"正在游泳");
    }}

注意:一个类实现多个接口的时候,每个接口中的抽象方法都要去实现,除非类用abstract修饰,为抽象类

提示IDEA中使用ctrl + i 可以快速实现接口

还有一种动物水陆空三栖,它是大白鹅

public class Goose extends Animal implements IRunning,ISwimming,IFlying{
    public Goose(String name) {
        super(name);
    }

    @Override
    public void fly() {
        System.out.println(this.name+"正在飞");
    }

    @Override
    public void run() {
        System.out.println(this.name+"正在跑");
    }

    @Override
    public void swim() {
        System.out.println(this.name+"正在漂在水上");
    }}

这段代码展现了Java面向对象编程中最常见的用法:一个类继承了一个父类,然后同时实现多个接口
继承表达的含义是is-a,而接口表达的含义是具有xxx的特性

猫是一种动物,具有会跑的特性
青蛙是一种动物,即能跑也能有用
大白鹅也是一种动物,技能跑,也能游,还能飞

有了接口之后,类的使用者就不需要去关注具体的类的属性是否符合,而只需要关心某个类是否具有某个特性/功能,如果有,就可以实现对应的接口
那么我们现在实现一个走路的方法

public class TestDemo1 {
    public static void walk(IRunning iRunning){
        System.out.println("我带着小伙伴去散步");
        iRunning.run();
    }

    public static void main(String[] args) {
        Cat cat = new Cat("小猫");
        walk(cat);
        
        Frog frog = new Frog("小青蛙");
        walk(frog);
    }}

输出结果
Java interface usage example analysis
只要是会跑的,带有跑这个属性特征的,都可以接受相应的对象

public class Robot implements IRunning{
    private String name;
    public Robot(String name){
        this.name = name;
    }
    @Override
    public void run() {
        System.out.println(this.name+"正在用轮子跑");
    }

    public static void main(String[] args) {
        Robot robot = new Robot("机器人");
        walk(robot);
    }}

Java interface usage example analysis
Java interface usage example analysis
故输出结果为
Java interface usage example analysis

接口之间的继承

在Java中,类和类之间是单继承的,一个类可以实现多个接口,接口与接口之间可以多继承。
即:用接口可以达到多继承的目的
接口可以继承一个接口,达到复用的效果。这里使用extends关键字

interface IRunning {
    void run();}interface ISwimming {
    void swim();}//两栖的动物,即能跑,也能游泳interface IAmphibious extends IRunning ISwimming {}class Frog implements IAmphibious {
    ...}

通过接口继承创建一个新的接口IAmphibious表示“两栖的”。
创建的Frog类就实现了这个两栖的接口

接口之间的继承就相当于把多个接口合并到了一起

接口使用的例子

我们在之前的数组中讲解过给数组排序,那么我们该如何给对象数组排序呢?
首先我们定义一个Student的类,然后重写一下String方法

public class Student {
    private String name;
    private int score;
    public Student(String name,int score){
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }}

我们再给定一个学生对象数组,根据这个对象数组中的元素进行排序
这里我们按照分数降序排序

public class Student {
    private String name;
    private int score;
    public Student(String name,int score){
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    public static void main(String[] args) {
        Student[] students = new Student[]{
                new Student("A",95),
                new Student("B",96), 
                new Student("C",97),
                new Student("D",98),
        };
    }}

那么按照我们之前的理解,数组中有一个可以供我们使用的sort方法,我们能否直接使用呢?

Arrays.sort(students);System.out.println(students);//运行结果:Exception in thread "main" java.lang.ClassCastException: class ClassArray.Student cannot be cast to class java.lang.Comparable (ClassArray.Student is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
	at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
	at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
	at java.base/java.util.Arrays.sort(Arrays.java:1041)
	at ClassArray.Student.main(Student.java:36)

Java interface usage example analysis
我们可以看到这里程序报错了,这里的意思是Student并没有实现Comparable的接口
那么这里的sort是进行普通数字的比较,大小关系明确,而我们指定的是两个学生对象的引用变量,这样的大小关系的指定是错误的,我们需要额外去人为规定对象中的比较元素
那么怎么实现呢?

我们可以用Student类实现Comparable接口,并实现其中的compareTo方法

public class Student implements Comparable<Student>{
    private String name;
    private int score;

    public Student(String name,int score){
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name=&#39;" + name + &#39;\&#39;&#39; +
                ", score=" + score +
                &#39;}&#39;;
    }

    @Override
    public int compareTo(Student o) {
        if (this.score>o.score){
            return -1;//      如果当前对象应排在参数对象之前,则返回小于0的数字
        } else if(this.score<o.score){
            return 1;//      如果当前对象应排在参数对象之后,则返回大于0的数字
        } else{
            return 0;//      如果当前对象和参数对象不分先后,则返回0      
        }
        
    }}

那么我们在这里重写了compareTo的方法,自己定义了比较的规则,我们就自己再去写一个sort的方法,去调用这个compareTo方法,真正意义上实现对 对象数组的排序
我们使用冒泡排序法

    public static void sort(Comparable[] array){//        这里要注意,虽然接口不能实例化对象,//        但是接口类型的引用变量可以指向它的实现类对象//        这里的实现类对象就是实现了这个接口的对象//        例如Comparable[] comparable = new Student[3];//        所以这里的参数就可以用Comparable[] array来接收
        for (int bound = 0;bound<array.length;bound++){
            for (int cur = array.length-1;cur>bound;cur--){
                if (array[cur-1].compareTo(array[cur])>0){
                    //这里就说明顺序不符合要求,交换两个变量的位置
                    Comparable tmp = array[cur-1];
                    array[cur-1] = array[cur];
                    array[cur] = tmp;
                }
            }
    }}

sort方法写好了,我们写一个main函数来测试一下

    public static void main(String[] args) {
        Student[] students = new Student[]{
                new Student("A",95),
                new Student("B",91),
                new Student("C",97),
                new Student("D",95),
        };
        System.out.println("sort前:"+Arrays.toString(students));
        sort(students);
        System.out.println("sort后:"+Arrays.toString(students));
    }

运行结果

E:\develop\Java\jdk-11\bin\java.exe "-javaagent:E:\IDEA\IntelliJ IDEA Community Edition 2021.3.2\lib\idea_rt.jar=65257:E:\IDEA\IntelliJ IDEA Community Edition 2021.3.2\bin" -Dfile.encoding=UTF-8 -classpath E:\JAVAcode\gyljava\Interface\out\production\Interface ClassArray.Studentsort前:[Student{name=&#39;A&#39;, score=95}, Student{name=&#39;B&#39;, score=91}, Student{name=&#39;C&#39;, score=97}, Student{name=&#39;D&#39;, score=95}]sort后:[Student{name=&#39;C&#39;, score=97}, Student{name=&#39;A&#39;, score=95}, Student{name=&#39;D&#39;, score=95}, Student{name=&#39;B&#39;, score=91}]

那么我们如果想要按照名字排序呢?也是可以的

import java.util.Arrays;import java.util.Comparator;/**
 * Created with IntelliJ IDEA.
 * Description: Hello,I would appreciate your comments~
 * User:Gremmie
 * Date: -04-13
 * Destination:利用Comparable的接口实现对 对象数组 选择性排序的功能
 */class Student implements Comparable<Student>{
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name=&#39;" + name + &#39;\&#39;&#39; +
                ", age=" + age +
                &#39;}&#39;;
    }

    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name);
    }}class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age-o2.age;
    }}class NameComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }}public class TestDemo {

    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("zhangsan",19);
        students[1] = new Student("lisi",8);
        students[2] = new Student("abc",78);
        AgeComparator ageComparator = new AgeComparator();
        NameComparator nameComparator = new NameComparator();
        
        
        //这里的方法sort是Array里面自带的,非常方便,
        //只需将我们写好的比较器传过去就好了
        System.out.println("排序前:"+Arrays.toString(students));
        Arrays.sort(students,nameComparator);
        System.out.println("排序后:"+Arrays.toString(students));
        Comparable<Student>[] studentComparable =students;
    }

    public static void main2(String[] args) {
        /*Student students1 = new Student("zhangsan",19);
        Student students2 = new Student("abc",78);
        if(students2.compareTo(students1) > 0) {
            System.out.println("fafaa");
        }*/


    }
    public static void main1(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("zhangsan",19);
        students[1] = new Student("lisi",8);
        students[2] = new Student("abc",78);
        System.out.println("排序前:"+Arrays.toString(students));
        Arrays.sort(students);
        System.out.println("排序后:"+Arrays.toString(students));
    }}

Clonable接口以及深拷贝

其作用如其名,是用来进行克隆的,Clonable是个很有用的接口。
Object类中存在一个clone方法,调用这个方法可以创建出一个对象,实现“拷贝”。
但是我们想要合法调用clone方法,就要先实现Clonable接口,
否则就会抛出CloneNotSupportedException异常

/**
 * Created with IntelliJ IDEA.
 * Description: Hello,I would appreciate your comments~
 * User:Gremmie
 * Date: -04-13
 * Destination:利用Clonable的接口实现clone方法,克隆含对象的对象
 */class Money implements Cloneable{
    public double money = 19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }}class Person implements Cloneable{
    public int id = 1234;
    public Money m = new Money();

    @Override
    public String toString() {
        return "Person{" +
                "id=&#39;" + id + &#39;\&#39;&#39; +
                &#39;}&#39;;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person) super.clone();
        tmp.m = (Money) this.m.clone();
        return tmp;
        //return super.clone();
    }}public class TestDemo {

    public static void main(String[] args) {
        Object o = new Person();

        Object o2 = new Money();


    }

    public static void main1(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person();
        Person person2 = (Person)person1.clone();
        System.out.println(person1.m.money);
        System.out.println(person2.m.money);
        System.out.println("=========================");
        person2.m.money = 99.99;
        System.out.println(person1.m.money);
        System.out.println(person2.m.money);
    }}

我们如果只是通过clone,那么就只是拷贝了Person的对象,但是Person中的money对象我们并没有拷贝下来,只是单纯拷贝下来一个地址,那么我们在这里就要进行深拷贝,讲Money类也接受Clonable接口,这样在调用clone方法的时候,money也会进行克隆

The above is the detailed content of Java interface usage example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete