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

How to define and use the Java interface

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the relevant knowledge of "how to define and use the Java interface". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. introduction

On the one hand, it is sometimes necessary to derive a subclass from several classes and inherit all their properties and methods. However, Java does not support multiple inheritance. With the interface, you can get the effect of multiple inheritance.

On the other hand, sometimes some common behavioral characteristics must be extracted from several classes, and there is no is-a relationship between them, just have the same behavioral characteristics. For example: mouse, keyboard, printer, scanner, camera, charger, MP3 machine, mobile phone, digital camera, mobile hard disk and so on all support USB connection.

2. Understanding

An interface is a specification, which defines a set of rules that reflect the real world "if you are / want to …" then you must be able to … " The mind of. Inheritance is a "yes" relationship, while interface implementation is a "can" relationship.

The essence of interface is contract, standard, specification, just like our law. After the formulation, everyone should abide by it.

III. Use

The interface is defined using the keyword interface.

In Java, the interface and the class are juxtaposed, or the interface can be understood as a special class. In essence, an interface is a special abstract class that contains only the definition of constants and methods (JDK7.0 and before), but no implementation of variables and methods.

Define the syntax format of the Java class: write extends first, then implements

Class SubClass extends SuperClass implements InterfaceA {}

An interface (interface) is a collection of abstract methods and constant value definitions.

How to define an interface:

JDK7 and previous: only global constants and abstract methods can be defined

All member variables in the interface are modified by public static final by default and can be omitted.

All abstract methods in the interface are decorated by public abstract by default.

Code demonstration:

Public interface Runner {int ID = 1; void start (); / / public abstract void start (); public void run (); / / public abstract void run (); void stop (); / / public abstract void stop ();}

JDK8: in addition to defining global constants and abstract methods, you can also define static methods and default methods.

1. Static method: decorate with the static keyword.

Static methods defined in an interface can only be called through the interface and execute its method body. We often use static methods in classes that use each other. You can find paired interfaces and classes like Collection/Collections or Path/Paths in the standard library.

two。 Default method: the default method is decorated with the default keyword. Can be called by implementing a class object. We provide new methods in existing interfaces while maintaining compatibility with old versions of the code. For example, java 8 API provides rich default methods for Collection, List, Comparator and other interfaces.

If a default method is defined in one interface and a method with the same name and parameter is defined in another interface (regardless of whether this method is the default method or not), an interface conflict occurs when the implementation class implements both interfaces at the same time. Solution: the implementation class must override the methods with the same name and parameters in the interface to resolve the conflict.

If a default method is defined in an interface, and a non-abstract method with the same name and parameter is also defined in the parent class, then the subclass calls the method with the same name and parameter in the parent class by default without overriding the method. There will be no conflict. Because the principle of class priority is observed at this time. Default methods with the same name and parameters in the interface are ignored.

How to call a method overridden in a parent class or interface in a method of a subclass (or implementation class)?

Code demonstration 1:

Public void myMethod () {method3 (); / / calls the self-defined overridden method super.method3 (); / / calls the default method CompareA.super.method3 () in the / / calling interface declared in the parent class; CompareB.super.method3 ();}

Code demo 2:

Interface Filial {/ / filial default void help () {System.out.println ("Mom, I'm coming to save you");}} interface Spoony {/ / infatuated default void help () {System.out.println ("wife, don't be afraid, I'm coming") }} class Father {public void help () {System.out.println ("son, just my wife!") Class Man extends Father implements Filial, Spoony {@ Override public void help () {System.out.println ("who am I supposed to be?") ; Filial.super.help (); Spoony.super.help ();}}

The constructor cannot be defined in the interface! Means that the interface cannot be instantiated.

The interface adopts multi-inheritance mechanism. Multiple interfaces can be implemented, which makes up for the limitation of Java single inheritance.

Format: class AA extends BB implements CC,DD,EE

In Java development, interfaces are used by letting classes implements.

If the implementation class overrides all abstract methods in the interface, the implementation class can be instantiated.

If the implementation class does not override all the abstract methods in the interface, the implementation class is still an abstract class.

Code demonstration:

/ * the implementation class SubAdapter must give the interface SubInterface and the implementation of all methods in the parent interface MyInterface. Otherwise, the SubAdapter still needs to be declared as abstract. * / interface MyInterface {String s = "MyInterface"; public void absM1 ();} interface SubInterface extends MyInterface {public void absM2 ();} public class SubAdapter implements SubInterface {public void absM1 () {System.out.println ("absM1");} public void absM2 () {System.out.println ("absM2");}}

Interfaces can be inherited from one interface to another, and more than one can be inherited.

A class can implement multiple unrelated interfaces.

Code demonstration:

Interface Runner {public void run ();} interface Swimmer {public double swim ();} class Creator {public int eat () {… }} class Man extends Creator implements Runner, Swimmer {public void run () { } public double swim () {. } public int eat () {. }}

Similar to inheritance relationships, there is polymorphism between interfaces and implementation classes

Code demonstration:

Public class Test {public static void main (String args []) {Test t = new Test (); Man m = new Man (); t.m1 (m); t.m2 (m); t.m3 (m);} public String M1 (Runner f) {f.run ();} public void m2 (Swimmer s) {s.swim ();} public void m3 (Creator a) {a.eat ();}

Anonymous implementation class anonymous object of the interface

Code demonstration:

Public class USBTest {public static void main (String [] args) {Computer com = new Computer (); / / 1. The non-anonymous object Flash flash = new Flash (); com.transferData (flash); / / 2 of the non-anonymous implementation class that created the interface. The anonymous object com.transferData (new Printer ()) of the non-anonymous implementation class that created the interface; / / 3. The non-anonymous object USB phone = new USB () {@ Override public void start () {System.out.println ("phone starts working") of the anonymous implementation class that created the interface } @ Override public void stop () {System.out.println ("Mobile phone ends work");}}; com.transferData (phone) / / 4. Anonymous object com.transferData (new USB () {@ Override public void start () {System.out.println ("mp3 starts working") of the anonymous implementation class that created the interface } @ Override public void stop () {System.out.println ("mp3 ends work");}}) }} class Computer {public void transferData (USB usb) {/ / USB usb = new Flash (); usb.start (); System.out.println ("details of specific data transfer"); usb.stop () }} interface USB {/ / constant: defines length, width, maximum and minimum transmission speed, such as void start (); void stop ();} class Flash implements USB {@ Override public void start () {System.out.println ("USB disk opens") } @ Override public void stop () {System.out.println ("USB disk ends working");}} class Printer implements USB {@ Override public void start () {System.out.println ("Printer on working") } @ Override public void stop () {System.out.println ("Printer ends working");} IV. Application-Agent Mode (Proxy) 1. Application scenario

Security proxy: blocks direct access to real roles.

Remote proxy: handles remote method calls (RMI) through the proxy class.

Delay loading: first load the lightweight proxy object, and then you really need to load the real object, such as you want to develop a large document view software, large documents have large pictures, it is possible that a picture has 100MB, when opening the file, it is impossible to show all the pictures, so you can use proxy mode, when you need to view pictures, use proxy to open large pictures.

two。 classification

Static proxy (statically define proxy class)

Dynamic proxy (dynamically generate proxy classes)

3. Code demonstration / / example 1: interface Network {public void browse ();} / proxy class class RealServer implements Network {@ Override public void browse () {System.out.println ("web browsing information on real server");}} / / proxy class class ProxyServer implements Network {private Network network; public ProxyServer (Network network) {this.network = network } public void check () {System.out.println ("check network connection, etc.");} public void browse () {check (); network.browse ();}} public class ProxyDemo {public static void main (String [] args) {Network net = new ProxyServer (new RealServer ()); net.browse () }} / / example 2: public class StaticProxyTest {public static void main (String [] args) {Proxy s = new Proxy (new RealStar ()); s.confer (); s.signContract (); s.bookTicket (); s.sing (); s.collectMoney () }} interface Star {void confer (); / / interview void signContract (); / / contract void bookTicket (); / / booking void sing (); / / singing void collectMoney () / / collect money} / / proxy class class RealStar implements Star {public void confer () {} public void signContract () {} public void bookTicket () {} public void sing () {System.out.println ("Star: singing ~") } public void collectMoney () {}} / / Agent class class Proxy implements Star {private Star real; public Proxy (Star real) {this.real = real;} public void confer () {System.out.println ("broker interview") } public void signContract () {System.out.println ("broker sign contract");} public void bookTicket () {System.out.println ("broker booking");} public void sing () {real.sing () } public void collectMoney () {System.out.println ("broker collects money");} V, comparison between interfaces and abstract classes No. Distinction point abstract class interface 1 defines classes that contain abstract methods are mainly collections of abstract methods and global constants 2 constitute constructors, abstract methods, general methods, constants, variable constants, abstract methods, (jdk8.0: default methods, static methods) 3 use subclasses inherit abstract classes (extends) subclasses implement interfaces (implements) 4 relational abstract classes can implement multiple interfaces can not inherit abstract classes But allow inheritance of multiple interfaces 5 common design pattern template methods simple factories, factory methods, proxy patterns 6 objects all instantiate objects through the polymorphism of objects, all instantiate objects through the polymorphism of objects 7 limit abstract classes have single inheritance limited interfaces without this limitation 8 is actually used as a standard or represents a capability 9 choices if both abstract classes and interfaces can be used Give priority to the use of interfaces, because to avoid the limitations of single inheritance if both abstract classes and interfaces can be used, give priority to the use of interfaces, because avoid the limitations of single inheritance. VI. Classic topic (troubleshooting) / / topic 1: interface A {int x = 0 } class B {int x = 1;} class C extends B implements A {public void pX () {System.out.println (x);} public static void main (String [] args) {new C (). PX ();} / / topic 2: interface Playable {void play ();} interface Bounceable {void play ();} interface Rollable extends Playable, Bounceable {Ball ball = new Ball ("PingPang") } class Ball implements Rollable {private String name; public String getName () {return name;} public Ball (String name) {this.name = name;} public void play () {ball = new Ball ("Football"); System.out.println (ball.getName ());}} "how the Java interface is defined and used" ends here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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