10

在一次讨论中,我的一位朋友告诉我,concrete methods would be allowed in java 1.8 in interfaces当时我想到了一个问题,即如果他们被允许,那么我们将如何区分这些方法。例如
,我有两个接口Animal.javaPet.java并且都有相同的具体方法,即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使用Test对象调用接口上的特定方法

public class Demo{
        public static void main(String[] args){

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

有什么建议么?或者在 java1.8 中是否有任何解决方案,因为我无法找到它的答案。

4

1 回答 1

9

You get a compile time error, unless you override eat in your Zoo class.

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

The latest and geatest jdk is here btw. And the syntax should be

default void eat(){
  System.out.println("Animal Start eating ....");
}
于 2013-04-12T10:50:23.420 回答