3

We know that we can't implement functions in interfaces in java.

I just tried

public interface InvoiceService {
public static void getData(){
 System.out.print("this is my data");
 }
}

I am able to execute this function, why is it like that? is it because the function is defined as static and static variables can be accessed using class name directly without creating an object?

asked Sep 15, 2015 at 8:53
5
  • 2
    Which JDK you are using ? Commented Sep 15, 2015 at 8:56
  • @sᴜʀᴇsʜᴀᴛᴛᴀ it is 1.8 Commented Sep 15, 2015 at 9:02
  • That's a new feature added in 1.8 :) Commented Sep 15, 2015 at 9:08
  • my whole life is a lie ;-) implementation in interfaces, it brings a new paradigm in java interfaces.. Commented Sep 15, 2015 at 9:11
  • Welcome to Narnia ;) Commented Sep 15, 2015 at 9:13

2 Answers 2

6

Because you might be using Java 8. In Java 8 you can add static methods in interfaces as well as default methods. Please read more about static and default methods in Java 8 documentation

answered Sep 15, 2015 at 8:56
Sign up to request clarification or add additional context in comments.

5 Comments

Good answer - posting some code examples would improve youir chances of upvotes.
@OldCurmudgeon Nope. you can't do that in older versions.
@sᴜʀᴇsʜᴀᴛᴛᴀ - Oops! Thanks for the heads-up.
default method is another type of method that is allowed in interfaces in Java8. They contain a body and can be overridden by implemented classes. However static methods cannot be override.
@DanyalSandeelo Did you go through the official doc provided in my answer?
1

is it because the function is defined as static and static variables can be accessed using class name directly without creating an object?

You are using Java8 it seems and you just implemented a default method

Yes, that method need not to ovveride by any of the implemented classes and belongs to interface.

And yes you need not to create an instance to access it. You can access it by interface name itself.

And since that is a static method you can use that as any normal utility method

From doc again,

If they add them as static methods, then programmers would regard them as utility methods, not as essential, core methods.

answered Sep 15, 2015 at 8:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.