Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of Interface usage examples of Java

2025-02-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of Java interface usage case analysis, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe everyone will gain something after reading this Java interface usage case analysis article. Let's take a look at it.

Interface

One-graph flow

The concept of interface and the summary of some knowledge points

Interface (English: Interface), in the JAVA programming language, is an abstract type, is a collection of abstract methods, interfaces are usually declared in interface. A class inherits the abstract methods of an interface by inheriting the interface.

Interfaces are not classes, and interfaces are written in a similar way to classes, but they belong to different concepts. Class describes the properties and methods of an object. The interface contains the methods that the class wants to implement.

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

The interface cannot be instantiated, but it can be implemented. A class that implements an interface must implement all the 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 be a null pointer, or they can be bound to an object implemented with this interface.

The similarities between an interface and a class

There can be more than one interface

The interface file is saved in the file at the end of .Java, and the file name uses the interface name.

The bytecode file for the interface is saved in the file at the end of .class

The bytecode file corresponding to the interface must be in a directory structure that matches the package name

The difference between interface and class

Interface cannot be used to instantiate an object

Interface has no construction method

All methods in the interface must be abstract methods, and non-abstract methods that can be modified with the default keyword in the interface after Java8

Interfaces cannot contain member variables, except for static and final variables

The concept that the interface is inherited by the class is not accurate, but it should be implemented by the class

Interface can implement what we call multi-inheritance

Some features of the interface

Every method in the interface is also implicitly abstract, so the method in the interface is implicitly specified as public abstract (only public abstract, other modifiers will report errors)

There are variables in the interface, but the variables in the interface will be implicitly specified as public static final variables (and can only be public, decorated with private will report a compilation error)

The methods in the interface cannot be implemented in the interface, and 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

A method in an abstract class can have a concrete executable statement, that is, the method body, which can implement the specific function of the method, but the method in the interface is not (for example: System.out.println ("Isimm super correlative!");

Member variables in an abstract class can be of various types, while member variables in an interface can only be of type public static final

Interfaces cannot contain static code blocks and the use of static methods (methods decorated with static), while abstract classes can have static code blocks and static methods

A class can inherit only one abstract class, while a class can implement multiple interfaces

So what we should pay attention to here is:

After JDK1.8, the interface is allowed to contain static methods and method bodies, as well as specific implementation methods, which we call "default methods" and are decorated with the default keyword

After JDK1.9, methods are allowed to be defined as private, so that some reused code does not expose methods.

The purpose of the existence of an abstract class is to enable the compiler to better verify that we will not use the abstract class directly, but use its subclasses. if we accidentally create an object through the abstract class, the compiler will remind us in time.

Note: the above content can be roughly scanned, but it doesn't matter if you don't understand it. I will explain it for you one by one below, and then look back at these knowledge points will have a feeling of waking up.

So what is the interface in real life? It can be a USB port on a notebook, an electrical outlet, etc.

Then these interfaces are also different in terms of implementation and usage standards.

The computer's USB port can be plugged into: U disk, mouse, keyboard. All devices that comply with USB protocol

Power outlet Jack, can be plugged into: computer, TV, rice cooker … All equipment conforming to the specification

Through the above example, we can see that the interface is a common behavior standard, and when we implement it, as long as it conforms to the standard, it can be used in general. In Java, an interface can be seen as a common specification for multiple classes and a reference data type

rule of grammar

The definition format of the interface is basically the same as that of the definition class. Replacing the class keyword with the interface keyword defines an interface.

Public interface interface name {/ / abstract method public abstract void method1 (); / / public abstract is a fixed collocation, so you can not write public void method2 (); abstract void method3 (); void method4 (); / / Note: all the above-mentioned writing methods in the interface are abstract methods, so method4 is cleaner to write code in this way.

Tip:

When you create an interface, the naming of the interface usually begins with an uppercase I (read ai)

The naming of interfaces generally uses adjective words of part of speech.

Ali coding specification stipulates that methods and properties in the interface do not add any modifiers to keep the code clean and tidy.

The use of the interface

An interface cannot be instantiated directly. There must be a class to implement it, implementing all the abstract methods in the interface.

Public class class name implements interface name {/ /...}

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

The class and interface of USB mouse and USB keyboard are used in notebook computer.

USB interface: includes the function of turning on and off the device

Notebook category: including switch function, using USB device function

Mouse class: implement USB interface and have click function

Keyboard class: implement USB interface and have input function

/ / USB interface public interface USB {void openDevice (); void closeDevice ();} / mouse class, implement USB interface public class Mouse implements USB {@ Override public void openDevice () {System.out.println ("turn on mouse");} @ Override public void closeDevice () {System.out.println ("turn off mouse") } public void click () {System.out.println ("mouse click");}} / / keyboard class, implement USB interface public class KeyBoard implements USB {@ Override public void openDevice () {System.out.println ("open keyboard");} @ Override public void closeDevice () {System.out.println ("close keyboard") } public void inPut () {System.out.println ("keyboard input");}} / / Notebook class: use USB device public class Computer {public void powerOn () {System.out.println ("Open laptop");} public void powerOff () {System.out.println ("turn off laptop") } 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 () }} / / Test class: public class TestUSB {public static void main (String [] args) {Computer computer = new Computer (); computer.powerOn (); / use mouse device computer.useDevice (new Mouse ()); / / use keyboard device computer.useDevice (new KeyBoard ()); computer.powerOff ();}}

Output:

Instanceof

In the above code example, instanceof is mentioned, but some of my friends may not quite understand it. I introduced it in my previous blog. I will explain it again for you.

Instanceof is a reserved keyword for Java, with objects on the left, classes on the right, and the return type of 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 yes, true is returned, otherwise false is returned

[points for attention in using instanceof]

Existing inheritance relationships, and the use of instanceof (including interface implementation)

[instanceof application scenario]

When you need to cast an object, you need to use instanceof to determine

Characteristics of Interfac

An interface type is a reference type, but an object that cannot directly new an interface

Public class TestUSB {public static void main (String [] args) {USB usb = new USB ();}} / / errors occur in compilation: USB is abstract and cannot be instantiated

Every method in the interface is an abstract method of public, that is, the method in the interface is implicitly specified as public abstract (only public abstract, other modifiers will report errors)

Public interface USB {/ / compilation error: the modifier private / / or java is not allowed here: the method body is missing, or the abstract private void openDevice () is declared; void closeDevice (); / / the standards of compilers in different JDK versions are different, and the error reports are different}

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 (); / / compilation failed: because the method in the interface defaults to abstract method / / Error: interface abstract method cannot have a body}

But here if we add a default, then we can implement the method body.

When overriding methods in an interface, you cannot use default as an access modifier

Public interface USB {void openDevice (); / / defaults to publicvoid closeDevice (); / / defaults to public} public class Mouse implements USB {@ Override void openDevice () {System.out.println ("turn on the mouse");} / /.} /.} / / the error will be reported when compiling here, and the default modifier cannot be used when overriding the openDevice method in USB.

Implement this interface, and the range of access qualifier modifiers for methods overriding this interface is larger than that in the interface.

The interface can contain variables, but the variables in the interface are automatically implicitly specified by the compiler as public static final variables

Public interface USB {double brand = 3.0 args / default: final public static modifies void openDevice (); void closeDevice ();} public class TestUSB {public static void main (String [] args) {System.out.println (USB.brand) / / can be accessed directly through the API name, indicating that the static / / writing method of the variable will report an error Java: the value USB.brand = 2.0 cannot be assigned to the final variable brand; / / it indicates that brand has a final attribute}}

There can be no static code blocks and constructors in the interface

Public interface USB {public USB () {} / compilation failed {} / / compilation failed void openDevice (); void closeDevice ();}

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

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

JDK8 specifies that the interface can contain the default method mentioned above.

Implement multiple interfaces

In Java, there is a single inheritance between classes, and 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 is demonstrated in code

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

Then we write a set of interfaces to represent "flying", "running" and "swimming".

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

So let's create a few specific animal classes to accept and implement these interfaces.

For example, cats can run.

Public class Cat extends Animal implements IRunning {public Cat (String name) {super (name);} @ Override public void run () {System.out.println ("kitten" + this.name+ "running");}}

Fish can swim.

Public class Fish extends Animal implements ISwimming {public Fish (String name) {super (name);} @ Override public void swim () {System.out.println ("Little Fish" + this.name+ "swimming");}}

And frogs can run and swim.

Public class Frog extends Animal implements IRunning,ISwimming {public Frog (String name) {super (name);} @ Override public void run () {System.out.println ("frog" + this.name+ "running");} @ Override public void swim () {System.out.println ("frog" + this.name+ "swimming");}}

Note: when a class implements multiple interfaces, the abstract methods in each interface must be implemented, unless the class is decorated with abstract and is an abstract class.

It is suggested that the interface can be realized quickly by using ctrl + I in IDEA.

There is also a kind of amphibious animal, which is a big white goose.

Public class Goose extends Animal implements IRunning,ISwimming,IFlying {public Goose (String name) {super (name);} @ Override public void fly () {System.out.println (this.name+ "flying");} @ Override public void run () {System.out.println (this.name+ "running") } @ Override public void swim () {System.out.println (this.name+ is "floating on the water");}}

This code shows the most common use in Java object-oriented programming: a class inherits a parent class and then implements multiple interfaces at the same time

The meaning of inheritance expression is is-a, while the meaning of interface expression is that it has the characteristics of xxx

A cat is an animal with the ability to run.

A frog is an animal that can run and be useful.

The big white goose is also an animal. It can run, swim and fly.

With the interface, the consumers of the class do not need to care about whether the properties of the specific class match, but only need to care about whether a class has a certain feature / function. If so, the corresponding interface can be implemented.

So now we have a way to walk.

Public class TestDemo1 {public static void walk (IRunning iRunning) {System.out.println ("I take my buddy for a walk"); iRunning.run ();} public static void main (String [] args) {Cat cat = new Cat ("kitten"); walk (cat); Frog frog = new Frog ("little frog"); walk (frog);}}

Output result

As long as they can run and have the attribute of running, they can accept the corresponding object.

Public class Robot implements IRunning {private String name; public Robot (String name) {this.name = name;} @ Override public void run () {System.out.println (this.name+ "running on wheels");} public static void main (String [] args) {Robot robot = new Robot ("robot"); walk (robot);}}

Therefore, the output result is

Inheritance between interfaces

In Java, there is a single inheritance between classes. A class can implement multiple interfaces, and interfaces can inherit multiple interfaces.

That is, the purpose of multi-inheritance can be achieved by using interfaces.

The interface can inherit an interface to achieve the effect of reuse. The extends keyword is used here

Interface IRunning {void run ();} interface ISwimming {void swim ();} / / amphibians can run and swim interface IAmphibious extends IRunning ISwimming {} class Frog implements IAmphibious {...}

Create a new interface IAmphibious that represents "amphibious" through interface inheritance.

The created Frog class implements this amphibious interface.

Inheritance between interfaces is equivalent to merging multiple interfaces together.

Examples of interface usage

We talked about sorting an array in the previous array, so how do we sort the array of objects?

First let's define a class for Student, and then rewrite the String method

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 +'}';}}

Let's give an array of student objects and sort them according to the elements in the array of objects.

Here we sort them in descending order of scores.

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

So according to our previous understanding, there is a sort method that we can use in the array, can we use it directly?

Arrays.sort (students); System.out.println (students); / / Operation result: 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)

We can see that the program reported an error here, which means that Student does not implement the interface of Comparable.

So the sort here is to compare ordinary numbers, and the size relationship is clear, while we specify the reference variables of two student objects, which is wrong, so we need to specify the comparison elements in the object artificially.

So how to achieve it?

We can use the Student class to implement the Comparable interface and implement the compareTo method in it

Public class Student implements Comparable {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 / / if the current object should be ranked before the parameter object, return a number less than 0} else if (this.score0) {/ / this means that the order is not in accordance with the requirements. Exchange the position of the two variables Comparable tmp = array [cur-1]; Array [cur-1] = array [cur] Array [cur] = tmp;}

The sort method is written, so let's write a main function to test it.

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 ("before sort:" + Arrays.toString (students)) Sort (students); System.out.println ("after sort:" + Arrays.toString (students));}

Running result

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

So what if we want to sort by name? It's also possible.

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: use the interface of Comparable to selectively sort the array of objects * / class Student implements Comparable {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 {@ Override public int compare (Student o1, Student o2) {return o1.ageMuo2.age;}} class NameComparator implements Comparator {@ 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 () / / the method sort here is included in Array, so it is very convenient. / / just pass the comparator we have written to System.out.println ("before sorting:" + Arrays.toString (students)); Arrays.sort (students,nameComparator); System.out.println ("after sorting:" + Arrays.toString (students)); Comparable [] 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 ("before sorting:" + Arrays.toString (students)); Arrays.sort (students); System.out.println ("after sorting:" + Arrays.toString (students));} Clonable interface and deep copy

Its function, like its name, is for cloning, and Clonable is a very useful interface.

There is a clone method in the Object class that can be called to create an object that implements "copy".

But if we want to call the clone method legally, we must first implement the Clonable interface

Otherwise, a CloneNotSupportedException exception will be thrown

/ * Created with IntelliJ IDEA. * Description: Hello,I would appreciate your comments~ * User:Gremmie * Date:-04-13 * Destination: use the interface of Clonable to implement the clone method and clone the object containing the object * / 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);}}

If we only copy the Person object through clone, but we didn't copy the money object in Person, we just copied an address, so we have to make a deep copy here, saying that the Money class also accepts the Clonable interface, so that when the clone method is called, the money will also be cloned.

This is the end of the article on "Java Interface usage example Analysis". Thank you for your reading! I believe you all have a certain understanding of the knowledge of "Java interface usage case analysis". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report