Interface中定义方法

一般我们都会认为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。


  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值