day10-接口的私有方法的定义和使用
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
package com.inmind.interface_private04;
|
||||
|
||||
public class Demo04 {
|
||||
public static void main(String[] args) {
|
||||
//直接测试静态方法和私有静态方法
|
||||
MyInterfae.method4();
|
||||
MyInterfae.method5();
|
||||
//注意:接口中的私有内容,是无法访问的,只能给它自己的默认方法或者静态方法访问
|
||||
//MyInterfae.sameStaticMethod();
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.inmind.interface_private04;
|
||||
/*
|
||||
JDK9中提供了私有方法的使用
|
||||
接口的私有方法定义和使用
|
||||
格式:
|
||||
private 返回值类型 私有方法名(参数列表){
|
||||
|
||||
}
|
||||
|
||||
作用:接口中私有方法的作用,是给接口中默认方法来调用的,也就是说私有方法是将默认方法中
|
||||
相同的内容抽取出来,同时静态方法也可以做相同的操作
|
||||
*/
|
||||
public interface MyInterfae {
|
||||
void method1();//抽象方法
|
||||
default void method2(){
|
||||
System.out.println("不同功能1");
|
||||
sameMethod();
|
||||
}
|
||||
default void method3(){
|
||||
System.out.println("不同功能2");
|
||||
sameMethod();
|
||||
};
|
||||
|
||||
//私有方法,将默认方法中相同的功能抽取出来
|
||||
private void sameMethod(){
|
||||
System.out.println("相同功能1");
|
||||
System.out.println("相同功能2");
|
||||
System.out.println("相同功能3");
|
||||
System.out.println("相同功能4");
|
||||
}
|
||||
|
||||
static void method4(){
|
||||
System.out.println("静态方法不同功能1");
|
||||
sameStaticMethod();
|
||||
}
|
||||
|
||||
static void method5(){
|
||||
System.out.println("静态方法不同功能2");
|
||||
sameStaticMethod();
|
||||
}
|
||||
|
||||
private static void sameStaticMethod(){
|
||||
System.out.println("静态方法相同功能1");
|
||||
System.out.println("静态方法相同功能2");
|
||||
System.out.println("静态方法相同功能3");
|
||||
System.out.println("静态方法相同功能4");
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user