Avi is a senior developer with a passion for Java technologies… http://www.aviyehuda.com/ Avi is a DZone MVB and is not an employee of DZone and has posted 25 posts at DZone. You can read more from them at their website. View Full User Profile

Java Interface Rules

02.16.2010
| 11278 views |
  • submit to reddit

Let’s start with a short Java question. Below 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 and 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
Methods
  • Can be only public and are by default.
  • Can not be static
  • Can not be Final

From http://www.aviyehuda.com/

5
Your rating: None Average: 5 (1 vote)
Published at DZone with permission of Avi Yehuda, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Richard Grin replied on Tue, 2010/02/16 - 9:50am

Members (of the first level) are necessarily public in an interface; they cannot be protected.

Avi Yehuda replied on Tue, 2010/02/16 - 5:17pm in response to: Richard Grin

Hi Richard

your definatly right.

I'll fix it in the article.

 

Thanks for correcting me.

Jeroen Wenting replied on Wed, 2010/02/17 - 5:46am

Anyone who passed the SCJP exam should know this.

Stephane Vaucher replied on Wed, 2010/02/17 - 11:47pm in response to: Jeroen Wenting

Funny, I was going to say that only someone who passed the SCJP exam would know this. Mostly because anyone else wouldn't care. On another case of testing useless tidbits of Java related knowledge, I would have asked what would happen if a class were to implement two interfaces both declaring a constant with the same name.

Jeroen Wenting replied on Thu, 2010/02/18 - 2:51am in response to: Stephane Vaucher

So you consider people knowing the rules for type declarations to be something people shouldn't care about? Because that's what we're talking about here.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.