Java interface 接口 新特性
1 package com.bytezreo.interfacetest; 2 3 public class SubClass2 { 4 public static void main(String[] args) { 5 SubClass s = new SubClass(); 6 //s.method1(); 7 //SubClass.method1(); 8 9 //接口中定义的静态方法,只能通过接口来调用。 10 11 InterfaceTest2.method1(); 12 13 //通过实现类的对象,可以调用接口中的默认方法 14 //如果实现类重写了接口中的默认方法,调用时,仍然调用的是重写以后的方法。 15 s.method2(); 16 17 //如果 子类(或实现类)继承的父类和实现的接口中声明了同名同参数的方法, 18 //那么子类在没有重写此方法的情况下,默认调用的是父类中同名同参的方法 19 // ------->类优先原则 20 21 //如果实现类 实现了多个接口,而这个多个接口定义了同名同参数的方法, 22 //那么在实现类没有重写此方法的情况下,报错----->接口冲突 23 24 //必须在实现类中重写此方法 25 s.method3(); 26 27 //SubClass.method2(); 28 29 30 31 } 32 33 } 34 class SubClass extends SuperClass implements InterfaceTest2,CompareB{ 35 36 public void method2() { 37 38 System.out.println("SubClass:上海"); 39 } 40 41 @Override 42 public void method3() { 43 44 System.out.println("SubClass:深圳"); 45 } 46 //如何在子类(实现类)的方法中调用父类,接口被重写的方法 47 public void myMethod() { 48 49 method3(); //自己定义的重写方法 50 super.method3(); // 调用父类中声明的方法 51 52 //调用接口中的默认方法 53 InterfaceTest2.super.method3(); 54 CompareB.super.method3(); 55 56 57 } 58 59 60 61 }
1 package com.bytezreo.interfacetest; 2 3 /** 4 * 5 * @Description interface 接口 新特性 6 * @author Bytezero·zhenglei! Email:420498246@qq.com 7 * @version 8 * @date 下午11:06:32 9 * @ 10 * 还可以定义 静态方法 默认方法 11 */ 12 public interface InterfaceTest2 { 13 14 //静态方法 15 public static void method1() { 16 17 System.out.println("CompareA:北京"); 18 } 19 20 //默认方法 21 public default void method2() { 22 23 System.out.println("CompareA:上海"); 24 } 25 26 default void method3() { 27 28 System.out.println("CompareA:上海"); 29 } 30 31 32 }
1 package com.bytezreo.interfacetest; 2 3 public class SuperClass { 4 5 public void method3(){ 6 7 System.out.println("SuperClass:北京"); 8 } 9 10 }
1 package com.bytezreo.interfacetest; 2 3 public interface CompareB { 4 5 default void method3(){ 6 7 System.out.println("CompareB:上海"); 8 } 9 10 }

本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15370057.html
浙公网安备 33010602011771号