This question already has answers here:
Are defaults in JDK 8 a form of multiple inheritance in Java?

(8个答案)



Virtual Extension Methods in upcoming Java 8 release

(5个答案)


已关闭8年。




在一次讨论中,我的一个 friend 告诉我concrete methods would be allowed in java 1.8 in interfaces当时是一个问题,即如果允许,那么我们将如何区分这些方法。
我有两个接口(interface)Animal.javaPet.java,并且都具有相同的具体方法i-e eat()
   public interfaces Animal{

        void eat(){
                System.out.println("Animal Start eating ....");
        }
   }

   public interfaces Pet{

        void eat(){
                System.out.println("Pet Start eating ....");
        }
   }

现在,我的Zoo.java既实现了这两个功能,又没有覆盖
    public class Zoo() implements Pet , Animal{
             //Now name method is a part of this class
   }

现在这是我的困惑。如何使用animal对象在接口(interface)Test上调用特定方法
public class Demo{
        public static void main(String[] args){

                 Zoo zoo = new Zoo();
                 zoo.eat();    //What would be the output
        }
 }

有什么建议么?还是在java1.8中对此有任何解决方案,因为我找不到答案。

最佳答案

您会得到一个编译时错误,除非您在Zoo类中重写eat。

java: class defaultMethods.Zoo inherits unrelated defaults for eat() from types Pet and Animal

最新,最漂亮的jdk是here btw。语法应该是
default void eat(){
  System.out.println("Animal Start eating ....");
}

09-10 05:50
查看更多