2

i was studied Java in oracle website. on that, i saw the example like

public class Horse { public String identifyMyself() { return "I am a horse."; } } public interface Flyer { default public String identifyMyself() { return "I am able to fly."; } } public interface Mythical { default public String identifyMyself() { return "I am a mythical creature."; } } public class Pegasus extends Horse implements Flyer, Mythical { public static void main(String... args) { Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); } } 

Can i write interface like this? I hope that i can only write abstract functions in interface. then why in oracle website they are gave example like this?

5

3 Answers 3

7

This feature is avaialble in java 8, it is called default method or defender method.

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

Find more about default method here.

java 8 snapshoot version is available jdk8 Build b129 .


There is one common question that people ask about default methods when they hear about the new feature for the first time: "What if the class implements two interfaces and both those interfaces define a default method with the same signature?".

but it is handled during compile time, get more explanation with example Here

Sign up to request clarification or add additional context in comments.

6 Comments

oh k... so i can declare normal function also in interface ah?
are you thinking about diamond problem?
Yup. Now I have no idea which function will be called. With the pure interfaces and single inheritance I always knew.
It is handled on compilation. Get an explantion here
There is no diamond problem with defender methods. Interfaces can't have state, defender methods can' be final, and you'll be forced by the compiler to choose which implementation you want if you implement two interfaces with a common defender method.
|
1

In Java 8, this is possible. And, it's called as default methods in the interfaces.

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

Check here for more details

Comments

0

As other SO users saying its available from java 8 .

but otherwise ..

No you cant , in the interface all the methods ar abstract methods by default .

Hope that Helps .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.