天天看點

java 1.8 override,接口Java1.8中的具體方法

java 1.8 override,接口Java1.8中的具體方法

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.

解決方案

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

}