2

Here is my simple code from a Java Tutorial.

public interface AnimalIntf {

    default public String identifyMyself(){
        return "I am an animal.";
    }

}

I get an error: illegal start of type interface methods cannot have body. The method is default and the default keyword is used at the beginning of the method signature. Could you please explain to me what is wrong?

10
  • What JDK version are you using? Commented Oct 23, 2014 at 19:46
  • @Jeffrey Bosboom, JDK 1.6 Commented Oct 23, 2014 at 19:48
  • 7
    You need JDK 8 to use default methods. Commented Oct 23, 2014 at 19:49
  • Surprisingly, you seem to be the first person to ask this question (or maybe the SO search is so useless it can't find the duplicate). Commented Oct 23, 2014 at 19:57
  • 1
    Well, Oracle’s tutorial says it on the start page: “The Java Tutorials primarily describe features in Java SE 8. For best results, download JDK 8 Commented Oct 27, 2014 at 9:31

3 Answers 3

5

Default interface methods were introduced in Java 8, so you need a JDK that supports Java 8 or later.

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

Comments

1

You must use Java 8 or above to have default implementations in interfaces. Instead you could use an abstract class. But even then, you wouldn't use the default keyword.

2 Comments

Oh, you meant if you're using an abstract class instead, you don't use default there. Sorry about that.
I have found this, the link could be helpful while determining which one to use, an interface or an abstract class: docs.oracle.com/javase/tutorial/java/IandI/abstract.html
0

Strange things are happening... After the JDK update to version 8 both on computer and in IDE settings, the code compiles OK, but the IDE still marks the line

default public String identifyMyself(){

as error. And there were still errors while trying to use the interface, asking to override the default method in the class that implements the interface.

public class Dragon implements Animal{    
}

2 hours later I got tired of trying to fix my NetBeans v.6.9.1 and downloaded NetBeans v8.0.1. Now I am fine :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.