zoukankan      html  css  js  c++  java
  • interface中定义default方法和static方法

    interface的default方法和static方法

    • 接口中可以定义static方法,可通过接口名称.方法名()调用,实现类不能继承static方法;
    • 接口中可以定义default方法,default修饰的方法有方法体,表示这个方法的默认实现,子类可以直接调用,可以选择重写或者不重写;
    • 当实现类实现的多个接口中,有方法签名相同的default方法时,必须重写该方法;

      接口一:

    package com.skd.interfacemethod;
    
    /**
     * @Description
     * @Author virgosnail
     * @Date 2018/12/12
     */
    
    public interface Human {
    
        /**
         * 必须被重写
         */
        void oldMethod();
    
        /**
         * 实现类可以选择重写,也可以不重写
         */
        default void hi(){
            System.out.println("interface default method");
        }
    
        /**
         * 不能被实现类重写
         */
        static void hello(){
            System.out.println("interface static method");
        }
    }

      接口二:

    package com.skd.interfacemethod;
    
    /**
     * @Description
     * @Author virgosnail
     * @Date 2018/12/12 20:59
     */
    
    public interface Humen {
    
        default void hi(String aa){
            System.out.println("interface default method");
        }
    }

      实现类:

    package com.skd.interfacemethod;
    
    /**
     * @Description
     * @Author virgosnail
     * @Date 2018/12/12
     */
    
    public class Person implements Human,Humen {
    
        @Override
        public void oldMethod() {
    
        }
    
        /**
         * 实现的多个接口中有方法签名相同的default 方法时,实现类必须重写该方法
         */
        @Override
        public void hi() {
    
        }
        /**
         * 实现类不能继承接口的static 方法
         */
    }

      测试类:

    package com.skd.interfacemethod;
    
    /**
     * @Description
     * @Author virgosnail
     * @Date 2018/12/12
     */
    
    public class Test {
        public static void main(String[] args) {
            // interface 的 default 方法通过实现类的实例对象调用
            new Person().hi();
            // interface 的 static 方法通过 接口名称.方法名称直接调用
            Human.hello();
    
        }
    }
  • 相关阅读:
    【C#进阶系列】06 类型和成员基础
    纪中5日T1 1564. 旅游
    纪中17日T1 2321. 方程
    纪中17日T2 2322. capacitor
    纪中10日T1 2313. 动态仙人掌
    纪中14日听课小结 图论 最短路 二分图 差分约束
    一个抓猫的游戏 消遣GAME 持续更新中!
    洛谷P1464 Function  HDU P1579 Function Run Fun
    洛谷P1976 鸡蛋饼
    纪中12日T1 2307. 选择
  • 原文地址:https://www.cnblogs.com/virgosnail/p/10111075.html
Copyright © 2011-2022 走看看