接口默认方法和静态方法
默认方法
1interface MyInterface1 { 2 3 default String method1() { 4 return "myInterface1 default method"; 5 } 6} 7 8class MyClass{ 9 public String method1() { 10 return "myClass method"; 11 } 12} 13 14/** 15 * 父类和接口中都有相同的方法,默认使用父类的方法,即类优先 16 * @author 莫雨朵 17 * 18 */ 19class MySubClass1 extends MyClass implements MyInterface1{ 20 21} 22 23@Test 24public void test1() { 25 MySubClass1 mySubClass1=new MySubClass1(); 26 System.out.println(mySubClass1.method1());//myClass method 27}
如果类的父类的方法和接口中方法名字相同且参数一致,子类还没有重写方法,那么默认使用父类的方法,即类优先
1interface MyInterface1 { 2 3 default String method1() { 4 return "myInterface1 default method"; 5 } 6} 7 8interface MyInterface2 { 9 10 default String method1() { 11 return "myInterface2 default method"; 12 } 13} 14 15/** 16 * 如果类实现的接口中有名字相同参数类型一致的默认方法,那么在类中必须重写 17 * @author 莫雨朵 18 * 19 */ 20class MySubClass2 implements MyInterface1,MyInterface2{ 21 22 @Override 23 public String method1() { 24 return MyInterface1.super.method1(); 25 } 26 27} 28 29@Test 30public void test2() { 31 MySubClass2 mySubClass2=new MySubClass2(); 32 System.out.println(mySubClass2.method1());//myInterface1 default method 33}
如果类实现的接口中有名字相同参数类型一致的默认方法,那么在类中必须重写
静态方法
1interface MyInterface1 { 2 static String method2() { 3 return "interface static method"; 4 } 5} 6 7@Test 8public void test3() { 9 System.out.println(MyInterface1.method2());//interface static method 10}
重复注解
1@Retention(RetentionPolicy.RUNTIME) 2@Target(ElementType.METHOD) 3public @interface MAnnotation { 4 String name() default ""; 5 int age(); 6} 7 8public class AnnotataionTest { 9 10 @Test 11 public void test() throws Exception { 12 Class<AnnotataionTest> clazz=AnnotataionTest.class; 13 Method method = clazz.getMethod("good", null); 14 MAnnotation annotation = method.getAnnotation(MAnnotation.class); 15 System.out.println(annotation.name()+":"+annotation.age()); 16 } 17 18 @MAnnotation(name="tom",age=20) 19 public void good() { 20 21 } 22}
以前我们是这样使用注解,当要在一个方法上标注两个相同的注解时会报错,java8允许使用一个注解来存储注解,可以实现一个注解重复标注
1@Retention(RetentionPolicy.RUNTIME) 2@Target(ElementType.METHOD) 3@Repeatable(MAnnotations.class)//使用@Repeatable来标注存储注解的注解 4public @interface MAnnotation { 5 String name() default ""; 6 int age(); 7} 8 9@Retention(RetentionPolicy.RUNTIME) 10@Target(ElementType.METHOD) 11public @interface MAnnotations { 12 MAnnotation[] value(); 13} 14 15public class AnnotataionTest { 16 17 @Test 18 public void test() throws Exception { 19 Class<AnnotataionTest> clazz=AnnotataionTest.class; 20 Method method = clazz.getMethod("good"); 21 MAnnotation[] mAnnotations = method.getAnnotationsByType(MAnnotation.class); 22 for (MAnnotation annotation : mAnnotations) { 23 System.out.println(annotation.name()+":"+annotation.age()); 24 } 25 } 26 27 @MAnnotation(name="tom",age=20) 28 @MAnnotation(name="jack",age=25) 29 public void good() { 30 31 } 32}