search
HomeJavajavaTutorialUnderstand the Java interface in one article

This article brings you relevant knowledge about Java, which mainly introduces issues related to interfaces, including the introduction and use of interfaces and the application of proxy mode, as well as interfaces and Let’s take a look at the comparison between abstract classes and other contents. I hope it will be helpful to everyone.

Understand the Java interface in one article

Recommended study: "java Video Tutorial"

1. Introduction

On the one hand, Sometimes it is necessary to derive a subclass from several classes and inherit all their properties and methods. However, Java does not support multiple inheritance. With interfaces, you can get the effect of Multiple inheritance.
On the other hand, sometimes it is necessary to extract some common behavioral characteristics from several classes, and there is no is-a relationship between them, they just have the same behavioral characteristics. For example: mice, keyboards, printers, scanners, cameras, chargers, MP3 players, mobile phones, digital cameras, mobile hard drives, etc. all support USB connections.

2. Understand

An interface is a specification, which defines a set of rules that embodies the principle of "if you are/want to..., you must be able to..." in the real world. Thought. Inheritance is a "is it" relationship, while interface implementation is a "can it" relationship.

The essence of the interface is a contract, standard, specification, just like our laws. Once formulated, everyone must abide by it.

3. Use

The interface is defined using the keyword interface.

In Java, interfaces and classes have a parallel relationship, or the interface can be understood as a special class. In essence, an interface is a special abstract class that only contains the definitions of constants and methods (JDK7.0 and before), without the implementation of variables and methods.
Define the syntax format of Java class: Write extends first, then implements

class SubClass extends SuperClass implements InterfaceA{ }

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

How to define the interface:

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

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

Code demonstration:

public interface Runner {
  int ID = 1;//public static final 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: Use the static keyword to modify it.
    Static methods defined in the interface can only be called through the interface and execute their method bodies. We often use static methods in classes that are used together with each other. You can find pairs of interfaces and classes like Collection/Collections or Path/Paths in the standard library.
  2. Default method: The default method is modified with the default keyword. Can be called by implementing a class object. We provide new methods in existing interfaces while maintaining compatibility with older versions of code. For example: Java 8 API provides rich default methods for Collection, List, Comparator and other interfaces.
    ● If one interface defines a default method, and another interface also defines a method with the same name and the same parameters (regardless of whether this method is the default method), when the implementation class implements both interfaces, Will appear: Interface conflict.
    Solution: The implementation class must override the method with the same name and the same parameters in the interface to resolve the conflict.
    ● If an interface defines a default method, and the parent class also defines a non-abstract method with the same name and parameters, then the subclass will call the method in the parent class by default if it does not override this method. Methods with the same name and parameters will not cause conflicts. Because at this time we abide by: Class Priority Principle. Default methods in the interface with the same name and parameters are ignored.
    ● How to call the overridden method in the parent class or interface in the method of the subclass (or implementation class)?

Code Demonstration 1:

public void myMethod(){
		method3();//调用自己定义的重写的方法
		super.method3();//调用的是父类中声明的
		//调用接口中的默认方法
		CompareA.super.method3();
		CompareB.super.method3();
	}

Code Demonstration 2:

interface Filial {// 孝顺的
	default void help() {
		System.out.println("老妈,我来救你了");
	}}interface Spoony {// 痴情的
	default void help() {
		System.out.println("媳妇,别怕,我来了");
	}}class Father{
	public void help(){
		System.out.println("儿子,就我媳妇!");
	}}class Man extends Father implements Filial, Spoony {
	@Override
	public void help() {
		System.out.println("我该就谁呢?");
		Filial.super.help();
		Spoony.super.help();
	}	}

Constructors cannot be defined in interfaces! It means that the interface cannot be instantiated.

 接口采用多继承机制。可以实现多个接口 ,弥补了Java单继承性的局限性。
格式:class AA extends BB implements CC,DD,EE;

 Java开发中,接口通过让类去实现(implements)的方式来使用。
 如果实现类覆盖了接口中的所有抽象方法,则此实现类就可以实例化 。
 如果实现类没有覆盖接口中所有的抽象方法,则此实现类仍为一个抽象类。

代码演示:

/*
实现类SubAdapter必须给出接口SubInterface以及父接口MyInterface
中所有方法的实现。否则,SubAdapter仍需声明为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”);}}

 接口与接口之间可以继承,而且可以多继承。

 一个类可以实现多个无关的接口。

代码演示:

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() {……}}

 与继承关系类似,接口与实现类之间存在多态性

代码演示:

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

 接口的匿名实现类匿名对象

代码演示:

public class USBTest {
	public static void main(String[] args) {
		
		Computer com = new Computer();
		//1.创建了接口的非匿名实现类的非匿名对象
		Flash flash = new Flash();
		com.transferData(flash);
		
		//2. 创建了接口的非匿名实现类的匿名对象
		com.transferData(new Printer());
		
		//3. 创建了接口的匿名实现类的非匿名对象
		USB phone = new USB(){
			@Override
			public void start() {
				System.out.println("手机开始工作");
			}
			@Override
			public void stop() {
				System.out.println("手机结束工作");
			}			
		};
		com.transferData(phone);
		
		
		//4. 创建了接口的匿名实现类的匿名对象
		
		com.transferData(new USB(){
			@Override
			public void start() {
				System.out.println("mp3开始工作");
			}

			@Override
			public void stop() {
				System.out.println("mp3结束工作");
			}
		});
	}}class Computer{	
	public void transferData(USB usb){//USB usb = new Flash();
		usb.start();		
		System.out.println("具体传输数据的细节");		
		usb.stop();
	}		}interface USB{
	//常量:定义了长、宽、最大最小的传输速度等	
	void start();	
	void stop();	}class Flash implements USB{
	@Override
	public void start() {
		System.out.println("U盘开启工作");
	}
	@Override
	public void stop() {
		System.out.println("U盘结束工作");
	}	}class Printer implements USB{
	@Override
	public void start() {
		System.out.println("打印机开启工作");
	}
	@Override
	public void stop() {
		System.out.println("打印机结束工作");
	}	}

四、应用:代理模式(Proxy)

1. 应用场景

 安全代理:屏蔽对真实角色的直接访问。

 远程代理:通过代理类处理远程方法调用(RMI)。

 延迟加载:先加载轻量级的代理对象,真正需要再加载真实对象,比如你要开发一个大文档查看软件,大文档中有大的图片,有可能一个图片有100MB,在打开文件时,不可能将所有的图片都显示出来,这样就可以使用代理模式,当需要查看图片时,用proxy来进行大图片的打开。

2. 分类

 静态代理(静态定义代理类)
 动态代理(动态生成代理类)

3. 代码演示

//举例一:interface Network {
    public void browse();
    }// 被代理类class RealServer implements Network { @Override
    public void browse() {
    System.out.println("真实服务器上
    网浏览信息");
    } }// 代理类class ProxyServer implements Network {
    private Network network;
    public ProxyServer(Network network) {
    this.network = network; }
    public void check() {
    System.out.println("检查网络连接等操作");}
    public void browse() {
    check();
    network.browse();
    } }public class ProxyDemo {
    public static void main(String[] args) {
    Network net = new ProxyServer(new
    RealServer());
    net.browse();
    } }//举例二: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();// 面谈
	void signContract();// 签合同
	void bookTicket();// 订票
	void sing();// 唱歌
	void collectMoney();// 收钱}//被代理类class RealStar implements Star {
	public void confer() {
	}
	public void signContract() {
	}
	public void bookTicket() {
	}
	public void sing() {
		System.out.println("明星:歌唱~~~");
	}
	public void collectMoney() {
	}}//代理类class Proxy implements Star {
	private Star real;
	public Proxy(Star real) {
		this.real = real;
	}
	public void confer() {
		System.out.println("经纪人面谈");
	}
	public void signContract() {
		System.out.println("经纪人签合同");
	}
	public void bookTicket() {
		System.out.println("经纪人订票");
	}
	public void sing() {
		real.sing();
	}
	public void collectMoney() {
		System.out.println("经纪人收钱");
	}}

五、接口和抽象类之间的对比

No. 区别点 抽象类 接口
1 定义 包含抽象方法的类 主要是抽象方法和全局常量的集合
2 组成 构造方法、抽象方法、普通方法、常量、变量 常量、抽象方法、(jdk8.0:默认方法、静态方法)
3 使用 子类继承抽象类(extends) 子类实现接口(implements)
4 关系 抽象类可以实现多个接口 接口不能继承抽象类,但允许继承多个接口
5 常见设计模式 模板方法 简单工厂、工厂方法、代理模式
6 对象 都通过对象的多态性产生实例化对象 都通过对象的多态性产生实例化对象
7 局限 抽象类有单继承的局限 接口没有此局限
8 实际 作为一个模板 是作为一个标准或是表示一种能力
9 选择 如果抽象类和接口都可以使用的话,优先使用接口,因为避免单继承的局限 如果抽象类和接口都可以使用的话,优先使用接口,因为避免单继承的局限

六、经典题目(排错)

//题目一: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();
    } }//题目二: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());
    } }

推荐学习:《java视频教程

The above is the detailed content of Understand the Java interface in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Why does the browser fail to correctly process the 401 status code when developing a WebSocket server using Netty?Why does the browser fail to correctly process the 401 status code when developing a WebSocket server using Netty?Apr 19, 2025 pm 07:21 PM

在使用Netty开发WebSocket服务器时,可能会遇到浏览器在尝试连接时未能正确处理服务器返回的401状态码的情况。 �...

Java compilation failed: What should I do if the javac command cannot generate the class file?Java compilation failed: What should I do if the javac command cannot generate the class file?Apr 19, 2025 pm 07:18 PM

Java compilation failed: Running window javac command cannot generate class file Many Java beginners will encounter this problem during the learning process: running window...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development?How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development?Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

Java compilation error: How do package declaration and access permissions change after moving the class file?Java compilation error: How do package declaration and access permissions change after moving the class file?Apr 19, 2025 pm 07:12 PM

Packages and Directories in Java: The logic behind compiler errors In Java development, you often encounter problems with packages and directories. This article will explore Java in depth...

Is JWT suitable for dynamic permission change scenarios?Is JWT suitable for dynamic permission change scenarios?Apr 19, 2025 pm 07:06 PM

JWT and Session Choice: Tradeoffs under Dynamic Permission Changes Many Beginners on JWT and Session...

How to properly configure apple-app-site-association file in pagoda nginx to avoid 404 errors?How to properly configure apple-app-site-association file in pagoda nginx to avoid 404 errors?Apr 19, 2025 pm 07:03 PM

How to correctly configure apple-app-site-association file in Baota nginx? Recently, the company's iOS department sent an apple-app-site-association file and...

What are the differences in the classification and implementation methods of the two consistency consensus algorithms?What are the differences in the classification and implementation methods of the two consistency consensus algorithms?Apr 19, 2025 pm 07:00 PM

How to understand the classification and implementation methods of two consistency consensus algorithms? At the protocol level, there has been no new members in the selection of consistency algorithms for many years. ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.