Java 8中允許接口中包含具有具體實現的方法,該方法稱爲默認方法
,默認方法使用 default
關鍵字修飾。
接口默認方法與靜態方法
接口中的默認方法其實在一定程度上是違背了接口原本存在的意義。
一、默認方法
1、僅實現接口
// 接口
public interface MyInterface {
// 默認方法
default String getName() {
return "MyInterface接口的getName默認方法";
};
}
// 實現類,如果不重寫getName方法,默認使用接口中的實現方式
public class MyInterfaceImp implements MyInterface{
}
public class InterfaceTest {
@Test
public void test1() {
MyInterface myInterface = new MyInterfaceImp();
System.out.println(myInterface.getName());
}
}
2、繼承一個類並實現接口
若一個接口中定義了一個默認方法,而另外一個父類又定義了一個同名的方法時。如果一個父類提供了具體的實現,那麼接口中具有相同名稱和參數的默認方法會被忽略。
public class ParentClass {
public String getName() {
return "父類中的同名方法!";
}
}
public class MyInterfaceImp extends ParentClass implements MyInterface{
}
3、實現兩個接口
如果一個父接口提供一個默認方法,而另一個接口也提供了一個具有相同名稱和參數列表的方法(不管方法是否是默認方法),那麼必須覆蓋
該方法來解決衝突。
public interface MyInterface1 {
default String getName() {
return "MyInterface2的getName默認方法!";
}
}
public class MyInterfaceImp implements MyInterface,MyInterface1{
// 重寫MyInterface的getName方法
@Override
public String getName() {
return MyInterface.super.getName();
}
}
二、靜態方法
Java8 中,接口中允許添加靜態方法。
public interface MyInterface {
default String getName() {
return "MyInterface接口的getName默認方法";
};
static String getNickName() {
return "接口中的靜態方法getNickName";
}
}
@Test
public void test2() {
System.out.println(MyInterface.getNickName());
}
重複註解與類型註解
Java 8對註解處理提供了兩點改進:可重複的註解及可用於類型的註解。
一、重複註解
@Repeatable(MyAnnotation1.class) // 指定容器
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
// 默認值爲lcy
String value() default "lcy";
}
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation1 {
MyAnnotation[] value();
}
public class TestAnnotation {
@MyAnnotation("Hello")
@MyAnnotation("World")
public void print() {
}
@Test
public void test() throws Exception{
Class<TestAnnotation> clazz = TestAnnotation.class;
Method print = clazz.getMethod("print");
MyAnnotation[] mas = print.getAnnotationsByType(MyAnnotation.class);
for(MyAnnotation an : mas) {
System.out.println(an.value());
}
}
}
二、類型註解
// MyAnnotation用在String類型前
public void show(@MyAnnotation String args) {
}