Interface中定义方法

本文介绍从 JDK 1.8 开始,Java 接口新增的默认方法和静态方法特性。默认方法允许接口直接提供方法实现,而不需要实现类重写;静态方法则可以在不实例化接口的情况下直接调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般我们都会认为Interface只能写入抽象的方法,它的实现交给使用的该接口的类,但在JDK1.8 之后Interface可以定义方法了。。

Interface:

package Test;

public interface testInterface {
     
	//可以被使用该接口的类使用
	default void change1(){ 
		System.out.println("we can use the word default to achieve the method!! ");
	}
	
	//可以被接口自己使用,与使用类中的静态方法一样
	static void change2(){
    	   System.out.println("we can use the word static to achieve the method!!!");
       }
}

test

package Test;

public class testMethod implements testInterface{
    
	public static void main(String args[]){
        	  
        	 testMethod test = new testMethod();
        	 
        	 test.change1();
        	 testInterface.change2();//调用自身的静态方法
          }
}


结论:

    1.新的Interface可以调用自身的static方法(这一点类似于类),但无法调用其default(当然包括public)方法,这与Interface的最初定义是一致,因为Interface本身就是等待其他类          来实现的,无法调用自身还没有实现的接口。。
    2.Interface中声明为default的并且已经实现的方法可以被类调用,无须再实现。。
    3.Interface定义的方法只能通过static或者是default修饰符实现,不可以使用public。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值