Java Interface rules

Let’s start with a short Java question:

Bellow you can see the interface ‘Test’.
Which lines in that interface will be rejected by the compiler?

public interface Test{

	public static final int x1 = 3; 
	public static int x2 = 3; 

	static int x3 = 3; 
	int x4 = 3; 

	public int f5();

	int f6(); 
	public static int f7();
	private void f8();

	public final void f9();

	private static final int x5 = 3; 

The answer is:

lines: 7,8,9,10

I am sure that even many of the experienced java developers will not have a 100% success answering this question because it can be confusing.

1, 2, 3 and 4 are actually all the same – only constants are allowed and by default they are. For that reason, 10 is not allowed.
5, 6 are the same – only public and protected methods are allowed. By default they are public.

In short these are the rules for interfaces:
Member variables
Can be only public and are by default.
By default are static and always static
By default are final and always final

Can be only public and are by default.
Can NOT be static
Can Not be Final

5 Replies to “Java Interface rules”

  1. Are you sure that protected methods are permitted in Interface definitions ?

    Consider the following code

    public interface I {

    public void p1();

    protected void p2(); // won’t compile

  2. Hi Dave,
    You are definitely right.
    I have changed the article.
    Thanks very much for being alert.

  3. HI you said you updated the article in a reply to “Dave Cheney”. But i can still see in the description saying public and protected methods are allowed in the interfaces. Can you please update the description to avoid confusion. If i am wrong please correct me.


  4. You are right, I have fixed it in one place but forgot the other place.
    Thank you also for being alert.

  5. The java doc says: “the interface body can contain abstract methods, default methods, and static methods.”
    So methods in interfaces can be static, but have to be followed by braces.

Leave a Reply to Avi Cancel reply

Your email address will not be published.