有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我可以在接口中声明普通函数吗?

我在oracle网站上学习Java。在这方面,我看到的例子是

public class Horse {
   public String identifyMyself() {
      return "I am a horse.";
   }
}
public interface Flyer {
   default public String identifyMyself() {
       return "I am able to fly.";
   }
}
public interface Mythical {
   default public String identifyMyself() {
       return "I am a mythical creature.";
   }
}
public class Pegasus extends Horse implements Flyer, Mythical {
   public static void main(String... args) {
       Pegasus myApp = new Pegasus();
       System.out.println(myApp.identifyMyself());
   }
}

我可以这样写界面吗?我希望我只能在接口中编写抽象函数。那么为什么在甲骨文网站上他们会被这样举个例子呢


共 (3) 个答案

  1. # 1 楼答案

    正如其他SO用户所说,它可以从Java8获得

    但除此之外

    不可以,在界面中,默认情况下所有方法都是抽象方法

    希望有帮助

  2. # 2 楼答案

    在Java8中,这是可能的。而且,它在接口中被称为默认方法

    Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

    查看here了解更多详细信息

  3. # 3 楼答案

    此功能在java 8中可用,称为默认方法或defender方法

    Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

    查找有关默认方法here的更多信息

    java 8 Snapshot版本可用jdk8 Build b129


    当人们第一次听说这个新特性时,他们会问一个关于默认方法的常见问题:“如果这个类实现了两个接口,而这两个接口都定义了一个具有相同签名的默认方法怎么办?

    但它是在编译时处理的,请使用示例Here获得更多解释