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

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值