This article brings you relevant knowledge aboutJava, 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.
Recommended study: "java Video Tutorial"
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 ofMultiple 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.
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.
The interface is defined using the keyword
interface
.
In Java, interfaces and classes have aparallelrelationship, 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:Writeextends
first, thenimplements
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: onlyglobal constants and abstract methods can be defined
- Allmember variablesin the interface are modified by
public static final
by default and can be omitted.- Allabstract methodsin 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 definestatic methods and default methods.
- 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 likeCollection/Collections
orPath/Paths
in the standard library.- Default method: The default method is modified with the
default
keyword.Can be calledby 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 forCollection
,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("打印机结束工作"); } }
安全代理:屏蔽对真实角色的直接访问。
远程代理:通过代理类处理远程方法调用(RMI)。
延迟加载:先加载轻量级的代理对象,真正需要再加载真实对象,比如你要开发一个大文档查看软件,大文档中有大的图片,有可能一个图片有100MB,在打开文件时,不可能将所有的图片都显示出来,这样就可以使用代理模式,当需要查看图片时,用proxy来进行大图片的打开。
静态代理(静态定义代理类)
动态代理(动态生成代理类)
//举例一: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!