0
点赞
收藏
分享

微信扫一扫

Java8接口新特性

weipeng2k 2022-01-09 阅读 42

静态方法

public interface SuperInterfaceA {
	static void staticMethod() {
		System.out.println("SuperInterfaceA-->staticMethod");
	}
}
public class SubClass implements SuperInterfaceA{
}

public class TestNewFeatures {
	public static void main(String[] args) {
		// 使用接口来调用静态方法
		SuperInterfaceA.staticMethod();
}

默认方法

public interface SuperInterfaceA {	
	default void defaultMethod1() {
		System.out.println("SuperInterfaceA-->defaultMethod1");
	}
	default void defaultMethod2() {
		System.out.println("SuperInterfaceA-->defaultMethod2");
	}	
}
public interface SuperInterfaceB {
	default void defaultMethod2() {
		System.out.println("SuperInterfaceA.java-->defaultMethod2");
	}
}

public class SuperClass {
	public void defaultMethod2() {
		System.out.println("SuperClass-->defaultMethod2");
	}
}

public class SubClass1 implements SuperInterfaceA{	
}

/**
 * 父类和一个接口有同名同参数默认方法 
 *  子类可以不重写 遵循类优先原则
 */
public class SubClass2 extends SuperClass implements SuperInterfaceA{
	
}

/**
 *  两个接口有同名同参数默认方法 
 *  子类必须重写
 */
public class SubClass3 implements SuperInterfaceA, SuperInterfaceB{
	@Override
	public void defaultMethod2() {		
		System.out.println("SubClass3-->defaultMethod2");
	}
}

/**
 * 调用父类和接口中默认方法的技巧
 */
public class SubClass4 extends SuperClass implements SuperInterfaceA, SuperInterfaceB {
	public void callSuperMethod() {
		super.defaultMethod2();
		SuperInterfaceA.super.defaultMethod2();
		SuperInterfaceB.super.defaultMethod2();
	}
}

public class TestNewFeatures {
	public static void main(String[] args) {
		SubClass1 subClass1 = new SubClass1();
		subClass1.defaultMethod1();
		subClass1.defaultMethod2();
		
		SubClass2 subClass2 = new SubClass2();		
		subClass2.defaultMethod2();
		
		SubClass3 subClass3 = new SubClass3();		
		subClass3.defaultMethod2();
		
		SubClass4 subClass4 = new SubClass4();		
		subClass4.callSuperMethod();
	}
}

输出:
SuperInterfaceA-->defaultMethod1
SuperInterfaceA-->defaultMethod2
SuperClass-->defaultMethod2
SubClass3-->defaultMethod2
SuperClass-->defaultMethod2
SuperInterfaceA-->defaultMethod2
SuperInterfaceB-->defaultMethod2
举报

相关推荐

0 条评论