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{
//1
public static final int x1 = 3;
//2
public static int x2 = 3;
//3
static int x3 = 3;
//4
int x4 = 3;
//5
public int f5();
//6
int f6();
//7
public static int f7();
//8
private void f8();
//9
public final void f9();
//10
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
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





Comments
Kumar Keswani replied on Mon, 2010/12/27 - 8:43pm
Felipe R. Lore... replied on Mon, 2010/12/27 - 11:43pm
Sudhir Mongia replied on Tue, 2010/12/28 - 1:19am
Cosmin Mutu replied on Tue, 2010/12/28 - 2:11am
Now, I don`t wanna be a "beach" but ... c`mon guys, post a new design pattern, a bug fix, a configuration for some sort of framework, but do not re-iterate each feature of Java (which you can find in any java manual).
Java Interface Rules ... ok, why? What cool thing did you achieved with it?
People, stop posting just to have your posts on dzone.
Avi Yehuda replied on Tue, 2010/12/28 - 3:00am
in response to: sharpaw
That's the nice thing about the internet, you can choose by yourself which information is good for you and which is not.
Thanks for your response.
Avi Yehuda replied on Tue, 2010/12/28 - 3:12am
in response to: fv71917
I didn't quite understood your question.
You wrote that your compiler showed 4 errors.
That are exactly the same errors I have wrote in the post - lines 7,8,9,10.
Methods cannot be static, private or private. Members cannot be private.
So I don't quite see how it is different than what I wrote. please elaborate, I'd be happy to help.
Agim Rama replied on Tue, 2010/12/28 - 6:47am
Jus for the sake of completeness here another method signature, which does not work:
protected void protectedMethod();surprisingly the package method works:
void packageMethod();Jean-Baptiste Nizet replied on Tue, 2010/12/28 - 8:06am
in response to: gimi
The packageMethod is not package protected. It's public. All methods of an interface are public, either explicitely, or implicitely (i.e. by giving no visibility modifier).
Slim Ouertani replied on Tue, 2010/12/28 - 11:18am