Home > Java > javaTutorial > Let you understand Java interfaces (detailed examples)

Let you understand Java interfaces (detailed examples)

WBOY
Release: 2022-04-19 17:55:00
forward
3804 people have browsed it

This article brings you relevant knowledge about java, which mainly introduces issues related to interfaces, including the concept of interfaces and a summary of some knowledge points, grammatical rules, and the use of interfaces As well as the characteristics of the interface, etc., let’s take a look at them below. I hope it will be helpful to everyone.

Let you understand Java interfaces (detailed examples)

Recommended study: "java video tutorial"

Interface

One picture Stream
Let you understand Java interfaces (detailed examples)

#The concept of interface and summary of some knowledge points

Interface (English: Interface), in the JAVA programming language is an abstract type, a collection of abstract methods, and an interface is usually declared 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
  • Interface files are saved in files 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. After Java 8, non-abstract methods modified with the default keyword can be used in the interface.
  • The interface cannot contain member variables, except for static and final variables
  • The concept of an interface being inherited by a class is not accurate. To be precise, it should be implemented by a class.
  • Interfaces can realize 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 (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 be public, using private modification will report a compilation error)
  • In the interface The methods 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

In JDK1. Before 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 methods, but methods in interfaces can No (for example:
    System.out.println("I'm super corn!!");
  • )Member variables in abstract classes can be of
  • various types
  • , and the member variables in the interface can only be of type public static finalThe interface cannot contain static code blocks and the use of static methods (methods modified with static), and 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 you should pay attention here What's more:

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 keyword. Modification
After JDK1.9, methods are allowed to be defined as private, so that some reused codes will not expose the methods
The meaning of the existence of abstract classes is In order to allow the compiler to better verify, we generally do 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 an interface? It can be a USB port on a laptop, a power socket, etc.
Let you understand Java interfaces (detailed examples)
Let you understand Java interfaces (detailed examples)
Then these interfaces are also different in terms of implementation and usage standards

  • The USB port of the computer can be plugged into: U disk, mouse, keyboard...all devices that comply with the USB protocol
  • The power outlet jack can be plugged into: computers, TVs, rice cookers...all devices that comply with the specifications Device

We can see from the above examples: The interface is a public behavioral specification standard. When everyone implements it, as long as it meets the specification 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这样写代码更整洁}
Copy after login

Tips:

  1. When creating an interface, the name of the interface generally starts with the capital letter I (pronounced ai)
  2. The name of the interface generally uses adjectives Part-of-speech words
  3. According to the Alibaba coding standards, do not add any modifiers to the methods and attributes in the interface to keep the code clean

Use of interfaces

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

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

Note: Between subclasses and parent classes There is an inheritance relationship between extends, and there is an implementation relationship between classes and interfaces.

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

  1. USB interface: including the functions of opening and closing the device
  2. Notebook class: including the power on and off function and the function of using USB devices
  3. Mouse class: implements the USB interface and has the click function
  4. Keyboard class: implements the USB interface and has the 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();
    }}
Copy after login

Output:
Let you understand Java interfaces (detailed examples)

instanceof

In the above code example, instanceof is mentioned, some friends may not understand it. , I introduced it in the previous blog, and I will explain it to you again
instanceof is a reserved keyword in Java, with objects on the left and classes on the right, and the return type is Boolean type.
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
public class TestUSB {
    public static void main(String[] args){
        USB usb = new USB();
    }}//编译会出错:USB是抽象的,无法实例化
Copy after login

Let you understand Java interfaces (detailed examples)

  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 (can only be public abstract, other modifiers will report an error)
public interface USB {
    //编译出错:此处不允许使用修饰符private
    //或者是java: 缺少方法主体, 或声明抽象
    private void openDevice();
    void closeDevice();
    //不同JDK版本编译器的标准是不一样的,报错也是不一样的}
Copy after login
  1. The methods in the interface cannot be implemented in the interface, and can only be implemented by the class that implements the interface
public interface USB {
    void openDevice();
    
    //编译失败:因为接口中的方法默认为抽象方法
    //Error:接口抽象方法不能带有主体}
Copy after login

Let you understand Java interfaces (detailed examples)
But if we add a default here, then the method body can be implemented.
Let you understand Java interfaces (detailed examples)

  1. #When rewriting a method in an interface, you cannot use default as the access permission modification
public interface USB {void openDevice();//默认为publicvoid closeDevice();//默认为public}public class Mouse implements USB {
    @Override
    void openDevice(){
        System.out.println("打开鼠标");
    }
    
    //...}//这里编译会报错,重写USB中的openDevice方法时,不能使用默认修饰符
Copy after login

Let you understand Java interfaces (detailed examples)
implement this interface. 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 automatically and implicitly specified by the compiler as public static finalVariable
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属性
    }}
Copy after login

Let you understand Java interfaces (detailed examples)

  1. There cannot be static code blocks and constructors in the interface
public interface USB {
    public USB(){
    
    }//编译失败
    
    {
    
    }//编译失败
    
    void openDevice();
    void closeDevice();}
Copy after login

Let you understand Java interfaces (detailed examples)

  1. 接口虽然不是类,但是接口编译完成之后的字节码文件的后缀格式也是.class
  2. 如果类没有实现接口中的所有抽象方法,则类必须设置为抽象类
  3. JDK8中规定了接口中可以包含上面所说的default方法

实现多个接口

在Java中,类和类之间是单继承的,一个类只能由一个父类,即Java中不支持多继承,但是一个类可以实现多个接口。下面用代码来演示

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

然后我们再写一组接口,分别来表示“会飞的”“会跑的”“会游泳的”.

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

Let you understand Java interfaces (detailed examples)
那么接下来我们创建几个具体的动物类来接受并实现这些接口
比如,猫会跑

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

鱼会游泳

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

而青蛙即会跑又会游泳

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+"正在游泳");
    }}
Copy after login

注意:一个类实现多个接口的时候,每个接口中的抽象方法都要去实现,除非类用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+"正在漂在水上");
    }}
Copy after login

这段代码展现了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);
    }}
Copy after login

输出结果
Let you understand Java interfaces (detailed examples)
只要是会跑的,带有跑这个属性特征的,都可以接受相应的对象

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);
    }}
Copy after login

Let you understand Java interfaces (detailed examples)
Let you understand Java interfaces (detailed examples)
故输出结果为
Let you understand Java interfaces (detailed examples)

接口之间的继承

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

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

通过接口继承创建一个新的接口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 +
                '}';
    }}
Copy after login

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

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),
        };
    }}
Copy after login

那么按照我们之前的理解,数组中有一个可以供我们使用的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)
Copy after login

Let you understand Java interfaces (detailed examples)
我们可以看到这里程序报错了,这里的意思是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='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        if (this.score>o.score){
            return -1;//      如果当前对象应排在参数对象之前,则返回小于0的数字
        } else if(this.score<o.score><p>那么我们在这里重写了compareTo的方法,自己定义了比较的规则,我们就自己再去写一个sort的方法,去调用这个compareTo方法,真正意义上实现对 对象数组的排序<br>我们使用冒泡排序法</p>
<pre class="brush:php;toolbar:false">    public static void sort(Comparable[] array){//        这里要注意,虽然接口不能实例化对象,//        但是接口类型的引用变量可以指向它的实现类对象//        这里的实现类对象就是实现了这个接口的对象//        例如Comparable[] comparable = new Student[3];//        所以这里的参数就可以用Comparable[] array来接收
        for (int bound = 0;bound<array.length>bound;cur--){
                if (array[cur-1].compareTo(array[cur])>0){
                    //这里就说明顺序不符合要求,交换两个变量的位置
                    Comparable tmp = array[cur-1];
                    array[cur-1] = array[cur];
                    array[cur] = tmp;
                }
            }
    }}</array.length>
Copy after login

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));
    }
Copy after login

运行结果

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='A', score=95}, Student{name='B', score=91}, Student{name='C', score=97}, Student{name='D', score=95}]sort后:[Student{name='C', score=97}, Student{name='A', score=95}, Student{name='D', score=95}, Student{name='B', score=91}]
Copy after login

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

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='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @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));
    }}</student></student></student></student>
Copy after login

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='" + id + '\'' +
                '}';
    }

    @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);
    }}
Copy after login

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

推荐学习:《java视频教程

The above is the detailed content of Let you understand Java interfaces (detailed examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template