Home >Java >javaTutorial >How to define and use Java interfaces

How to define and use Java interfaces

PHPz
PHPzforward
2023-04-18 22:10:06865browse

    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 and embody the idea of ​​"if you are/want to..., you must be able to..." in the real world. 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 the

    interface to define it 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.

    The syntax format for defining Java classes: write extends first, then implements

    class SubClass extends SuperClass implements InterfaceA{ }

    The 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 by default public static finalModified, you can omit it.

    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.

    The 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 a default method is defined in an interface, and a method with the same name and the same parameters is also defined in another interface (regardless of whether this method is a default method), while implementing the class When these two interfaces are implemented, interface conflicts will occur. Solution: The implementation class must override the method 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 parameters is also defined in the parent class, then the subclass will not override this method without , the method with the same name and the same parameters in the parent class is called by default, and there will be no conflict problems. 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();
    	}

    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.

    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) way 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 the 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”);}
    }

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

    Similar to the inheritance relationship, there is polymorphism between the interface and the implementation class

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

    Anonymity of the interface Implement class anonymous object

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

    4. Application-proxy mode (Proxy)

    1. Application scenario

    • SecurityProxy: Block direct access to real roles.

    • Remote proxy: Handles remote method invocation (RMI) through the proxy class.

    • 延迟加载:先加载轻量级的代理对象,真正需要再加载真实对象,比如你要开发一个大文档查看软件,大文档中有大的图片,有可能一个图片有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());
        } 
    }

    The above is the detailed content of How to define and use Java interfaces. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete