java8接口写静态方法

Java 8 interface changes include static methods and default methods in interfaces. Prior to Java 8, we could have only method declarations in the interfaces. But from Java 8, we can have default methods and static methods in the interfaces.

Java 8接口更改包括接口中的静态方法和默认方法。 在Java 8之前,接口中只能有方法声明。 但是从Java 8开始,我们可以在接口中使用默认方法静态方法

Java 8接口 (Java 8 Interface)

Designing interfaces have always been a tough job because if we want to add additional methods in the interfaces, it will require change in all the implementing classes. As interface grows old, the number of classes implementing it might grow to an extent that it’s not possible to extend interfaces. That’s why when designing an application, most of the frameworks provide a base implementation class and then we extend it and override methods that are applicable for our application.

设计接口一直是一项艰巨的工作,因为如果我们想在接口中添加其他方法,则将需要对所有实现类进行更改。 随着接口的变老,实现它的类的数量可能会增加到无法扩展接口的程度。 这就是为什么在设计应用程序时,大多数框架都提供一个基本的实现类,然后我们对其进行扩展并覆盖适用于我们的应用程序的方法。

Let’s look into the default interface methods and static interface methods and the reasoning of their introduction in Java 8 interface changes.

让我们研究一下默认接口方法和静态接口方法,以及它们在Java 8接口更改中引入的原因。

Java接口默认方法 (Java Interface Default Method)

For creating a default method in java interface, we need to use “default” keyword with the method signature. For example,

为了在Java接口中创建默认方法,我们需要在方法签名中使用关键字“ default ”。 例如,

package com.journaldev.java8.defaultmethod;public interface Interface1 {void method1(String str);default void log(String str){System.out.println("I1 logging::"+str);}
}

Notice that log(String str) is the default method in the Interface1. Now when a class will implement Interface1, it is not mandatory to provide implementation for default methods of interface. This feature will help us in extending interfaces with additional methods, all we need is to provide a default implementation.

注意,log(String str)是Interface1的默认方法。 现在,当一个类将实现Interface1时,就不必为接口的默认方法提供实现。 此功能将帮助我们使用其他方法扩展接口,我们所需要的只是提供默认的实现。

Let’s say we have another interface with following methods:

假设我们还有一个使用以下方法的接口:

package com.journaldev.java8.defaultmethod;public interface Interface2 {void method2();default void log(String str){System.out.println("I2 logging::"+str);}}

We know that Java doesn’t allow us to extend multiple classes because it will result in the “Diamond Problem” where compiler can’t decide which superclass method to use. With the default methods, the diamond problem would arise for interfaces too. Because if a class is implementing both Interface1 and Interface2 and doesn’t implement the common default method, compiler can’t decide which one to chose.

我们知道Java不允许我们扩展多个类,因为它会导致“钻石问题”,编译器无法决定要使用哪种超类方法。 使用默认方法,接口也会出现菱形问题。 因为如果一个类同时实现Interface1Interface2且没有实现通用的默认方法,则编译器无法决定选择哪个方法。

Extending multiple interfaces are an integral part of Java, you will find it in the core java classes as well as in most of the enterprise application and frameworks. So to make sure, this problem won’t occur in interfaces, it’s made mandatory to provide implementation for common default methods of interfaces. So if a class is implementing both the above interfaces, it will have to provide implementation for log() method otherwise compiler will throw compile time error.

扩展多个接口是Java不可或缺的一部分,您可以在核心Java类以及大多数企业应用程序和框架中找到它。 因此,为确保此问题不会在接口中发生,必须将其提供为常见的默认接口方法的实现。 因此,如果一个类同时实现了上述两个接口,则必须为log()方法提供实现,否则编译器将抛出编译时错误。

A simple class that is implementing both Interface1 and Interface2 will be:

同时实现Interface1Interface2简单类将是:

package com.journaldev.java8.defaultmethod;public class MyClass implements Interface1, Interface2 {@Overridepublic void method2() {}@Overridepublic void method1(String str) {}@Overridepublic void log(String str){System.out.println("MyClass logging::"+str);Interface1.print("abc");}
}

Important points about java interface default methods:

有关Java接口默认方法的要点:

  1. Java interface default methods will help us in extending interfaces without having the fear of breaking implementation classes.Java接口默认方法将帮助我们扩展接口,而不必担心破坏实现类。
  2. Java interface default methods has bridge down the differences between interfaces and abstract classes.Java接口默认方法缩小了接口和抽象类之间的差异。
  3. Java 8 interface default methods will help us in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.Java 8接口的默认方法将帮助我们避免使用实用程序类,例如可以在接口本身中提供所有Collections类的方法。
  4. Java interface default methods will help us in removing base implementation classes, we can provide default implementation and the implementation classes can chose which one to override.Java接口默认方法将帮助我们删除基本实现类,我们可以提供默认实现,而实现类可以选择覆盖哪个实现。
  5. One of the major reason for introducing default methods in interfaces is to enhance the Collections API in Java 8 to support lambda expressions.在接口中引入默认方法的主要原因之一是增强Java 8中的Collections API以支持lambda表达式。
  6. If any class in the hierarchy has a method with same signature, then default methods become irrelevant. A default method cannot override a method from java.lang.Object. The reasoning is very simple, it’s because Object is the base class for all the java classes. So even if we have Object class methods defined as default methods in interfaces, it will be useless because Object class method will always be used. That’s why to avoid confusion, we can’t have default methods that are overriding Object class methods.如果层次结构中的任何类都具有具有相同签名的方法,则默认方法将变得无关紧要。 缺省方法不能覆盖java.lang.Object的方法。 推理非常简单,这是因为Object是所有java类的基类。 因此,即使我们将Object类方法定义为接口中的默认方法,也将是无用的,因为将始终使用Object类方法。 这就是为什么要避免混淆的原因,我们不能使用覆盖Object类方法的默认方法。
  7. Java interface default methods are also referred to as Defender Methods or Virtual extension methods.Java接口默认方法也称为Defender方法或虚拟扩展方法。

Java接口静态方法 (Java Interface Static Method)

Java interface static method is similar to default method except that we can’t override them in the implementation classes. This feature helps us in avoiding undesired results incase of poor implementation in implementation classes. Let’s look into this with a simple example.

Java接口静态方法与默认方法类似,不同之处在于我们无法在实现类中覆盖它们。 如果实现类中的实现不佳,此功能可帮助我们避免不良结果。 让我们通过一个简单的示例对此进行研究。

package com.journaldev.java8.staticmethod;public interface MyData {default void print(String str) {if (!isNull(str))System.out.println("MyData Print::" + str);}static boolean isNull(String str) {System.out.println("Interface Null Check");return str == null ? true : "".equals(str) ? true : false;}
}

Now let’s see an implementation class that is having isNull() method with poor implementation.

现在,让我们来看一个实现类,该类的isNull()方法的实现不佳。

package com.journaldev.java8.staticmethod;public class MyDataImpl implements MyData {public boolean isNull(String str) {System.out.println("Impl Null Check");return str == null ? true : false;}public static void main(String args[]){MyDataImpl obj = new MyDataImpl();obj.print("");obj.isNull("abc");}
}

Note that isNull(String str) is a simple class method, it’s not overriding the interface method. For example, if we will add @Override annotation to the isNull() method, it will result in compiler error.

注意isNull(String str)是一个简单的类方法,它没有覆盖接口方法。 例如,如果将@Override批注添加到isNull()方法,则将导致编译器错误。

Now when we will run the application, we get following output.

现在,当我们运行应用程序时,我们将得到以下输出。

Interface Null Check
Impl Null Check

If we make the interface method from static to default, we will get following output.

如果将接口方法从静态设置为默认值,则会得到以下输出。

Impl Null Check
MyData Print::
Impl Null Check

Java interface static method is visible to interface methods only, if we remove the isNull() method from the MyDataImpl class, we won’t be able to use it for the MyDataImpl object. However like other static methods, we can use interface static methods using class name. For example, a valid statement will be:

Java接口静态方法仅对接口方法可见,如果我们从MyDataImpl类中删除isNull()方法,则无法将其用于MyDataImpl对象。 但是,像其他静态方法一样,我们可以使用带有类名的接口静态方法。 例如,有效的语句将是:

boolean result = MyData.isNull("abc");

Important points about java interface static method:

有关Java接口静态方法的要点:

  1. Java interface static method is part of interface, we can’t use it for implementation class objects.Java接口静态方法是接口的一部分,我们不能将其用于实现类对象。
  2. Java interface static methods are good for providing utility methods, for example null check, collection sorting etc.Java接口静态方法非常适合提供实用程序方法,例如null检查,集合排序等。
  3. Java interface static method helps us in providing security by not allowing implementation classes to override them.Java接口静态方法通过不允许实现类覆盖它们来帮助我们提供安全性。
  4. We can’t define interface static method for Object class methods, we will get compiler error as “This static method cannot hide the instance method from Object”. This is because it’s not allowed in java, since Object is the base class for all the classes and we can’t have one class level static method and another instance method with same signature.我们无法为Object类方法定义接口静态方法,我们将得到编译器错误,因为“此静态方法无法从Object隐藏实例方法”。 这是因为在Java中是不允许的,因为Object是所有类的基类,并且我们不能有一个类级别的静态方法和另一个具有相同签名的实例方法。
  5. We can use java interface static methods to remove utility classes such as Collections and move all of it’s static methods to the corresponding interface, that would be easy to find and use.我们可以使用java接口静态方法删除实用程序类(例如Collections),并将其所有静态方法移动到相应的接口,这将很容易找到和使用。

Java功能接口 (Java Functional Interfaces)

Before I conclude the post, I would like to provide a brief introduction to Functional interfaces. An interface with exactly one abstract method is known as Functional Interface.

在结束本文之前,我想简要介绍一下Functional接口。 具有唯一一种抽象方法的接口称为功能接口。

A new annotation @FunctionalInterface has been introduced to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. It’s optional but good practice to use it.

引入了新的注释@FunctionalInterface,以将接口标记为Functional Interface。 @FunctionalInterface注释是一种避免在功能接口中意外添加抽象方法的工具。 这是可选的,但是使用它是一个好习惯。

Functional interfaces are long awaited and much sought out feature of Java 8 because it enables us to use lambda expressions to instantiate them. A new package java.util.function with bunch of functional interfaces are added to provide target types for lambda expressions and method references. We will look into functional interfaces and lambda expressions in the future posts.

功能接口是Java 8期待已久且广受欢迎的功能,因为它使我们能够使用lambda表达式实例化它们。 添加了带有功能接口束的新程序包java.util.function ,以提供lambda表达式和方法引用的目标类型。 在以后的文章中,我们将研究功能接口和lambda表达式。

翻译自: https://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method

java8接口写静态方法

java8接口写静态方法_Java 8接口更改–静态方法,默认方法相关推荐

  1. java 接口 静态方法_Java 8 接口静态方法

    Java 8 除了给接口带来了 默认方法之外,还给接口带来了 静态方法.而且,Java 8 中的静态方法还可以有具体的实现. 我们都知道,在 Java 7 及之前的版本中,接口 interface 是 ...

  2. JAVA接口返回面积_java – 将接口的返回值限制为实现类的范围

    我正在编写一个小型库,我有一些接口提供了一个返回值应该在指定范围内的方法.我如何明确禁止实现此方法的库的用户返回不在此范围内的值? 像这样的东西: //Library interface Favori ...

  3. java 接口 this参数_Java BiFunction 接口实例

    原标题:Java BiFunction 接口实例 www.baeldung.com/java-bifunction-interface 1. 简介 Java8 引入了函数式编程,可以把函数作为参数传入 ...

  4. java短信接口源码_java免费短信接口开发源码

    java免费短信接口开发源码 更多 作者:捷信通来源:www.jiexintong.cn日期:2014-07-30 17:08:51 微宏捷信通短信接口提供适应C#.Java..NET等多种主流开发语 ...

  5. java类引用接口的注释_java – 在接口类型上使用注释有什么好处?

    在这个 example中,注释类型(@interface)下面: @interface ClassPreamble { String author(); String date(); int curr ...

  6. java 接口 签名机制_java – 当接口A在其方法签名中定义接口B时

    -如何限制A的实现在方法签名中使用B的某个实现? 用例 这是一个Unit接口和两个实现它的枚举: public interface Unit { ... } public enum ForceUnit ...

  7. java 接口防刷_java轻量级接口限流/防刷插件

    简介 call-limit提供接口限流.防刷的功能,插件基于spring开发,在应用应用的任何一个逻辑层皆可使用(web.service.dao), 插件支持单机应用下的限流和分布式应用的限流(分布式 ...

  8. java接口源码_java collection接口源码

    package java.util; /* * 1.Collection接口是集合继承关系中的根接口(root interface),有些集合允许重复元素, * 有些集合有序,JDK不提供本接口的实现 ...

  9. java对外发布接口文档_java之接口文档规范

    一.xxxxxx获取指定任务爬取的所有url的接口 接口名称:xxxxxx获取指定任务爬取的所有url的接口 访问链接: http://IP:PORT/crwalTask/findUrlExcepti ...

最新文章

  1. Applet 大文件上传
  2. 什么样的产品适合跨境电商?这里告诉你答案!
  3. if you can not make a solid foundation
  4. 华为手机拍照后图库里无照片_EMUI的相册不这么用,还用什么智能手机?
  5. MFC源码不能设置断点调试
  6. 查看SVN当前登录用户
  7. 计算机学术会议英语作文,计算机专业资料——重要国际学术会议
  8. java 上传附件实例
  9. AI算法模型线上部署方法总结
  10. java8 update 91 有什么用_为什么java8还在被大量使用?
  11. DIS全球首款基于数字资产证券化交易生态系统
  12. java netcdf精度_NetCDF 介绍
  13. Serverless Computing Fass $ openwhisk快速部署、应用、实例
  14. HLOJ 2026 猴子吃桃
  15. LZ77压缩算法原理剖析
  16. java8新特性学习笔记(Lambda,stream(),filter(),collect(),map())
  17. docker安装mysql并配置文件_docker 安装mysql5.7 加my.cnf
  18. rj45 千兆接口定义_RJ45接口针脚定义(各种接口针脚定义)
  19. 计算机教室场地技术条,特殊教育学校功能室建设标准
  20. 两名老人接力营救轻生女子一人溺亡

热门文章

  1. Android adb不是内部或外部命令 问题解决
  2. [转载] JAVA出现空指针异常(初学者)
  3. I/O接口标准(1):LVTTL、LVCMOS、SSTL、HSTL
  4. elasticsearch监控平台cerebro-0.8.3 相关操作
  5. Python基础---循环、条件判断
  6. SpringBoot私人学习笔记
  7. zbb20170607 svn SVN服务器搭建和使用
  8. python之爬虫学习记录与心得
  9. POJ_2456_Agressive_cows_(二分,最大化最小值)
  10. SQLServer生成带数据的脚本