on public static members in java interface definition - say what?

Published 09-01-2007 8:28 PM | Agile_ph

At work, I've seen some Java code that defines an interface similar to this.

public interface ITestme {

public static String Name="Agile";

}

throws a warning if you don't initialize the member?!

and then, they refer to it as...

public class TestMeUser implements ITestme {

public void TestMethod()

{

String name = ITestme.Name;

System.out.println(name);

}

}

looks to me that it's more of a enum rather than an interface.

Everybody(well almost) who writes C# code knows that it isn't necessary(I think it's a syntax error) to include the access modifier for the fact that all C# interface members are implicitly public. So, does Java have a different definition of what an Interface is or is this some sort of an old school approach that wasn't taken out as Java moved up with different versions.

Filed under: ,

Comments

# lamia said on September 1, 2007 8:16 AM:

For your first example:

Hmmmm... Before enums where introduced in Java 5, this is one of the many ways we use enumeration. My preferred way though was to create a class like AnimalsEnum(prior to Java 5) or just put those final static members in some sort of abstract class. I'm not the best designer there is but if there is a chance for you to use the new feature(Which is nice) then do so.

For your second example:

Rules in overriding a method in Java says that you cannot make a method's access modifier less restrictive than the one you are inheriting(or implementing) from.  Taking out the access modifier there would put your method in "default" or "package-private" mode. Thus, a compiler error would be generated.

About Java interfaces:

all methods in a Java interface are implicitly "public abstract". For readability, most of us declare methods as "public" when creating an interface. Although this is redundant, it is good practice.

# Agile_ph said on September 2, 2007 9:21 AM:

it's good practice to declare methods public in an interface? interesting!