java 接口Java1.8中的具体方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15968987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
concrete methods in interfaces Java1.8
提问by Freak
During a discussion one of my friend tell me that concrete methods would be allowed in java 1.8 in interfacesthen at that time a question came into my mind i-e If they are allowed then How will we distinguish the methods.For example
I have two Interface Animal.javaand Pet.javaand both have same concrete method i-e eat()
在一次讨论中,我的一位朋友告诉我,concrete methods would be allowed in java 1.8 in interfaces当时我想到了一个问题,即如果允许,那么我们将如何区分这些方法。例如,
我有两个接口Animal.java,Pet.java并且它们都有相同的具体方法,即eat()
public interfaces Animal{
void eat(){
System.out.println("Animal Start eating ....");
}
}
public interfaces Pet{
void eat(){
System.out.println("Pet Start eating ....");
}
}
Now my Zoo.javaimplement both of these and didn't override
现在我Zoo.java实现了这两个并且没有覆盖
public class Zoo() implements Pet , Animal{
//Now name method is a part of this class
}
Now here is my confusion.How can I call a specific method on inteface animalusing Testobject
现在这是我的困惑。如何animal使用Test对象调用接口上的特定方法
public class Demo{
public static void main(String[] args){
Zoo zoo = new Zoo();
zoo.eat(); //What would be the output
}
}
Any suggestions? or is there any solution for this in java1.8 as I am unable to find its answer.
有什么建议?或者在 java1.8 中是否有任何解决方案,因为我无法找到它的答案。
采纳答案by NimChimpsky
You get a compile time error, unless you override eat in your Zoo class.
您会收到编译时错误,除非您在 Zoo 类中覆盖了eat。
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 ....");
}

