concrete methods in interfaces Java1.8 [duplicate]

做~自己de王妃 提交于 2019-12-10 03:54:48

问题


During a discussion one of my friend tell me that concrete methods would be allowed in java 1.8 in interfaces then 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.java and Pet.java and both have same concrete method 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 ....");
        }
   }

Now my Zoo.java implement both of these and didn't override

    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 animal using Test object

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.


回答1:


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 ....");
}


来源:https://stackoverflow.com/questions/15968987/concrete-methods-in-interfaces-java1-8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!