Skip to content

Instantly share code, notes, and snippets.

@khotyn
Last active January 3, 2016 18:29
Show Gist options
  • Save khotyn/8502914 to your computer and use it in GitHub Desktop.
Save khotyn/8502914 to your computer and use it in GitHub Desktop.
Java 8 中的接口的 default 关键字测试
package com.khotyn.java8;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* 测试 Java 8 中的接口的 default 功能
*
* @author khotyn 1/19/14 5:39 PM
*/
@RunWith(JUnit4.class)
public class DefaultTest {
@Test
public void 测试_default_的基本功能() {
Impl impl = new Impl();
Assert.assertEquals("A", impl.foo());
}
@Test
public void 测试多重实现() {
MultiImpl multiImpl = new MultiImpl();
Assert.assertEquals("C", multiImpl.foo());
}
@Test
public void 测试多重实现调用接口默认实现() {
MultiImplInvokeSuper multiImplInvokeSuper = new MultiImplInvokeSuper();
Assert.assertEquals("B", multiImplInvokeSuper.foo());
}
class Impl implements A {
}
class MultiImpl implements A, B {
/**
* 由于 A,B 中都有 String foo() 接口,不知道要调用哪个,所以实现类必须实现一下
*
* @return
*/
@Override
public String foo() {
return "C";
}
}
class MultiImplInvokeSuper implements A, B {
@Override
public String foo() {
return B.super.foo();
}
}
interface A {
default String foo() {
return "A";
}
}
interface B {
default String foo() {
return "B";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment