0

I've been wondering why it's allowed to do a code implementation in an interface, when interfaces are suppossed to contain no code implementation:

public interface someInterface{
String someString = "example"; 
}

I can make a class implement this interface, without getting an error:

public class someClass implements someInterface

How come?

asked Aug 29, 2013 at 18:38
3
  • To add to your wonder, Java 8 is on the way with default method implementation allowed. Commented Aug 29, 2013 at 18:43
  • @Ravinder really? At what point do we start calling them classes? I thought Java is supposed to be single inheritance... Commented Aug 29, 2013 at 18:49
  • @Cruncher You can read more at Introduction to Default Methods (Defender Methods) in Java 8. Commented Aug 31, 2013 at 10:38

3 Answers 3

8

You are allowed to declare constants in interfaces, which is what you have done. You have not implemented code.

Variables declared in interfaces are implicitly declared public static final.

The JLS, Section 9.3, covers this:

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

answered Aug 29, 2013 at 18:39
Sign up to request clarification or add additional context in comments.

2 Comments

So I guess I've mixed up implementation and initialization. The string in the example is only a variable initialization, and not code implementation, right?
Correct, it's just initialization of a constant, not implementing any methods.
0

According to java docs

Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

Here you are not defined any methods to implement.So you didn't get any error here.

answered Aug 29, 2013 at 18:43

Comments

0

There is no strict condition that an interface must have signatured methods.Remember there are Marker Interfaces too in java.

And secondly , You can declare variables inside interface.

And that variable someString assigned in a static context and shared across all the implemntations by that interface

Point is that the variables inside declared interface are implicitly static and final.You can use them.

answered Aug 29, 2013 at 18:39

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.