1

I would like to define a method in JAVA interface. The reason is that every time I implement interface the method is the same, but I need to implement two interfaces for particular classes. Example:

interface A
method A()

interface B
method B()

class first implements A,B

class second implements A

method A() has same body everywhere.

4
  • 3
    You can do that in Java 8 with the default keyword. You can't do it in earlier versions. docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html Commented Oct 1, 2014 at 12:40
  • 2
    Or you can use abstract class in instead of interface A Commented Oct 1, 2014 at 12:42
  • As long as it's only interface A that needs implementations, you can get away in java <8 by making it an abstract class and keeping B an interface Commented Oct 1, 2014 at 12:43
  • I was thinking about abstract classes but there will be more interfaces with defined methods that I would like to implement. Thanks for an answer khelwood, your comment was very helpful for me. Commented Oct 1, 2014 at 12:45

1 Answer 1

4

As of Java 8, you can put method implementations into interfaces. http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

interface A {
    default void aMethod() {
        // method body
    }
}

In earlier versions, you would have to make A a class instead of an interface. An abstract class if that suits your model better.

abstract class A {
     public void aMethod() {
          // method body
     }
}

class first extends A implements B {
    ...
}
Sign up to request clarification or add additional context in comments.

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.