St.Antario
St.Antario

Reputation: 27375

Anonymous class implementing an interface

I have the following interface:

public interface MessageFactory<T extends Message> {

    public T create(Session session);
}

when I define the class like this, Eclipse gives me the error in the comment below on that line:

public abstract class MessageType<T extends Message> implements MessageFactory<T>{

    public static final MessageType<ObjectMessage> PLAYER_REGISTER = new MessageType<ObjectMessage>() {

        @Override
        public ObjectMessage create(Session session) { //Error, remove @Override annotation
            //impl
        }
    };

    private MessageType(){ }
}

But if I copy-and-paste the create method from the interface into the class as an abstract method, the error goes away:

public abstract class MessageType<T extends Message> implements MessageFactory<T>{

    public static final MessageType<ObjectMessage> PLAYER_REGISTER = new MessageType<ObjectMessage>() {

        @Override
        public ObjectMessage create(Session session) {  //Fine
            //impl
        }
    };

    public abstract T create(Session session);

    private MessageType(){ }
}

What's wrong with anonymous classes implementing interfaces?

Upvotes: 1

Views: 459

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

Looks like an IDE bug of some kind; Java's compiler is perfectly happy with it. If I set up that situation and use Oracle's Java8 javac, it compiles just fine.

It's fine here on IDEOne using non-public classes, or if I create these files and compile them:

Message.java:

public class Message { }

ObjectMessage.java:

public class ObjectMessage extends Message { }

Session.java:

public class Session { }

MessageFactory.java:

public interface MessageFactory<T extends Message> {

    public T create(Session session);
}

MessageType.java:

public abstract class MessageType<T extends Message> implements MessageFactory<T>{

    public static final MessageType<ObjectMessage> PLAYER_REGISTER = new MessageType<ObjectMessage>() {

        @Override
        public ObjectMessage create(Session session) { //Error, remove @Override annotation
            return null;
        }
    };

    private MessageType(){ }
}

Upvotes: 3

Related Questions