接口组成更新
接口的组成
-
常量
public static final
-
抽象方法
public abstract
-
默认方法
-
静态方法
-
私有方法
接口组成更新了之后跟抽象类更加接近了
接口中默认方法
接口中默认方法的定义格式:
- 格式:public default 返回值类型 方法名(参数列表){}
- 范例:public default void shoe3(){}
接口中默认方法的注意事项:
- 默认方法不是抽象方法,所以不强制被重写,但是可以被重写,重写时去掉default关键字
- public 可以省略,default不能省略
接口中静态方法
接口中静态方法的定义格式:
- 格式:public static 返回值类型 方法名(参数列表){}
- 范例:public static void show(){}
接口中静态方法的注意事项:
- 静态方法只能通过接口名调用,不能通过实现类名或者对象名调用
- public 可以省略,static 不能省略
//接口类
public interface in {
void show1();
void show2();
default void show3(){
System.out.println("show3");
}
public static void show4(){
System.out.println("show 4");
}
}
//实现类
public class dame implements in {
@Override
public void show1() {
System.out.println("show");
}
@Override
public void show2() {
System.out.println("show2");
}
public static void main(String[] args) {
dame s = new dame();
s.show1();
s.show2();
s.show3();
//s.show4();//报错,不能被对象调用
in.show4();//可以被接口调用
}
}
接口中私有方法
接口中私有方法的定义格式
格式一:private 返回值类型 方法名(参数列表){}
范例一:private void show(){}
格式二:private static 返回值类型 方法名(参数列表){}
范例二:private static void method(){}
接口中私有方法的注意事项:
默认方法可以调用私有的静态方法和非静态方法
静态方法只能调用私有的静态方法
//主方法
public class dame implements in {
public static void main(String[] args) {
dame s = new dame();
s.show3();
//s.show4();//报错,不能被对象调用
in.show4();//可以被接口调用
s.show5();
in.show4();
}
//接口
public interface in {
default void show3(){
System.out.println("show1");
//show();//私有方法在默认方法中出现,避免重复
method();//静态私有方法,在默认方法中也可以使用
System.out.println("show5");
System.out.println("----------------------------");
}
public static void show4(){
System.out.println("show2");
method();//私有静态方法在静态方法中出现,避免重复
System.out.println("show4");
System.out.println("----------------------------");
}
default void show5(){
System.out.println("show3");
show();
System.out.println("show3");
System.out.println("----------------------------");
}
private void show(){//默认私有方法
System.out.println("show2");
System.out.println("show3");
System.out.println("show4");
}
private static void method(){//默认私有静态方法
System.out.println("show2");
System.out.println("show3");
System.out.println("show4");
}