zoukankan      html  css  js  c++  java
  • 类如何实现具有相同方法的两个接口

    问题:

    众所周知,Java中一个类可以同时实现多个接口,如果多个接口中有相同的抽象方法时,实现类实现的方法是哪个接口的??

    测试

    Interface1.java

    /**
     * @author liuyiyuan
     */
    public interface Interface2 {
        void method();
    
        default void method2(){
            System.out.println("Interface2的方法调用:");
            method();
        }
    }

    Interface2.java

    /**
     * @author liuyiyuan
     */
    public interface Interface1 {
        void method();
        //int method(); //不能通过编译
    
        default void method1(){
            System.out.println("Interface1的方法调用:");
            method();
        }
    }

    InterfaceImpl.java

    /**
     * @author liuyiyuan
     */
    public class InterfaceImpl implements Interface2, Interface1  {
        @Override
        public void method() {
            System.out.println("xxxxxxxxxxxxx");
        }
    
        public static void main(String[] args) {
            Interface1 anInterface = new InterfaceImpl();
            anInterface.method();
            anInterface.method1();
    
            Interface2 i2 = (Interface2) anInterface;
            i2.method();
            i2.method2();
        }
    }

    输出如下:

    结论

    • 实现了具有相同方法(名字相同、参数相同、返回类型相同)的多个接口时,这个方法实现是共用的
    • 具有相同方法时一定要重写,即使是default方法也要重写
    • 当方法参数不同时,方法之间为重载,互不影响
    • 当返回值不同时,会发生错误,不能编译
  • 相关阅读:
    C# 使用SMTP发送附件
    C# 获取文件名及扩展名
    邮件添加附件
    WPF 加载GIF动画
    IIS端口被占用 转载
    ReDim Preserve 的用途
    c# 构造函数执行顺序
    WriteLog
    SMS发送短信设置HttpWebRequest
    Directory.GetFiles
  • 原文地址:https://www.cnblogs.com/liuyiyuan/p/13832420.html
Copyright © 2011-2022 走看看