Amir Rachum
Amir Rachum

Reputation: 79655

Can an interface demand that a class define an internal enum?

I want to define an interface, so that all the classes implementing it will define an internal enum named Fields. Is that possible in Java?

EDIT: I am creating a dynamic web application using Java (Servlets/JSP). I am trying to get my models to all have save() methods, so that they will be stored in the database. To represent the data and the fields of, say, a user in the system, I want to use Map<User.Fields, Object>. But I want to put the save() method in an interface, so I want to make sure that all the saveable objects have a Fields enum. For example, the User class can define something like:

public class User {
    enum Fields { USERNAME, PASSWORD }
}

Upvotes: 1

Views: 229

Answers (4)

Suraj Chandran
Suraj Chandran

Reputation: 24791

No you can't .

Why not have the enum in the parent interface.

EDIT to answer the EDIT of question: You shouldn't do like this. Instead have a interface like this:

interface Saveable
{
    Object[] getSaveFields();
}

Just look for the memento pattern, it may help you.

Upvotes: 2

Ray Tayek
Ray Tayek

Reputation: 10003

no, but you can do something like:

    enum E {
        e1,e2
    }
    interface I{
        Enum getEnum();
    }
 interface I2 {
    EnumSet getEnums();
}
class I2Impl implements I2 {
    @Override public EnumSet getEnums() {
        return EnumSet.allOf(E.class);
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new IImpl().getEnum());
        System.out.println(new I2Impl().getEnums());
    }
}

Upvotes: 0

Bohemian
Bohemian

Reputation: 425198

One technique I've used to address this issue is is to define an enum-typed interface, so you can "join" a particular enum with a class, then define that enum with the subclass, like this:

public interface MySuper<T extends Enum<T>> {
    void someMethod(T someEnum);
}

public class MySubClass implements MySuper<MyEnum> {

    public static enum MyEnum {
        ONE, TWO, THREE
    }

    void someMethod(MyEnum myEnum) {
        // do something
    }
}

Oddly, you have to import static mypackage.MySubClass.MyEnum;

Upvotes: 0

Charlie
Charlie

Reputation: 7349

As Suraj said, nope, not possible. What is your intention by this however? If each subclass defines its own set of fields, You could force a getFields method, returning a Set of objects implementing another interface (and / or Enum). Or just going by names, are you needing the reflexions API (i.e. getClass().getDeclaredFields() )?

Upvotes: 0

Related Questions