Home > Java > javaTutorial > What are the custom usage methods of Java interface?

What are the custom usage methods of Java interface?

PHPz
Release: 2023-04-22 23:34:24
forward
1228 people have browsed it

What are the custom usage methods of Java interface?

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

Interfaces are specifications, which define a set of rules that embody "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 interfaces is contracts, standards, and specifications, just like our laws. Once formulated, everyone must abide by it.

3. Use

Interface is defined using the keyword interface.

In Java, interfaces and classes are in a parallel relationship, or interfaces 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{ }
Copy after login

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

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 its method body. 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 class objects. 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, An interface conflict will appear.
    Solution: The implementation class must override the method with the same name and 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 the same 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: the 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();
	}
Copy after login

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

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

The interface adopts multiple inheritance mechanism. Multiple interfaces can be implemented, making up for the limitations of Java's single inheritance.
Format: class AA extends BB implements CC,DD,EE;

In Java development, interfaces are implemented by classes (implements) to use.
If the implementation class covers all abstract methods in the interface, this implementation class can be instantiated.
If the implementation class does not cover all abstract methods in the interface, the implementation class is still an abstract class.

Code demonstration:

/*
实现类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”);}}
Copy after login

Interfaces can be inherited from each other, and multiple inheritances are possible.

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

Similar to the inheritance relationship, 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();}}
Copy after login

Anonymous implementation class anonymous object of interface

Code demonstration:

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("打印机结束工作");
	}	}
Copy after login

四、应用:代理模式(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("经纪人收钱");
	}}
Copy after login

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

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

The above is the detailed content of What are the custom usage methods of Java interface?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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