作者:溪谷小兵 | 来源:互联网 | 2023-06-27 22:05
一般我们都会认为Interface只能写入抽象的方法,它的实现交给使用的该接口的类,但在JDK1.8之后Interface可以定义方法了。。Interface:packageTest;public
一般我们都会认为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。