Java8接口新特性

静态方法

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值