Over a million developers have joined DZone.

Java Interface Rules

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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/

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}