Java: interface containing internal enumeration; Extend functionality in implementation classes

I have the following interface: @ h_ 502_ 2@package example; import java. awt. Point; public interface Thing { public enum MovingState { MOVING_LEFT,MOVING_UP,MOVING_RIGHT,MOVING_DOWN } public void setNewPosition(MovingState state); public Point getPosition(); }

And an implementation class:

The idea is to make the movingstate in thingimpl extend the movingstate from the thing interface (thus separating the actual implementation of the movestate from the interface)

This doesn't work – the movingstate enumeration in thingimpl affects the definition in the interface rather than extending it. Then the compiler complains that thingimpl is not abstract and does not override the abstract method setnewposition (thing. Movingstate) in thing

Is there a practical way to do what I want to achieve? Or does java have this capability at all?

Solution

What you really want to do is remove the enumeration declaration from the "thingimpl" class and move it all (including its constructor and getter) to the thing interface

Let your fields last in the enumeration and remember that they should not be touched

In this way, any content that wants to use the thing interface must use the enumeration defined in the interface - your problem is that you have effectively defined it twice, but it should enumerate java files on the interface (which will only be used for this interface) or at the public level (using public enumeration instead of public classes) If other functions outside your interface can reasonably be expected to use it, you will become a public enumeration - in my opinion, map Entry is a wrong nested interface because other classes can be used to map external key / value pairs, so it should be its own interface, but we must live in it:(

I don't think this is really your idea - I think the behavior you specify on the thing interface is very good. You really don't want to touch the movingstate enumeration because it's good However, if you think you need to use a different implementation of movingstate, you can implement an interface called movingstate so that you can rename your enumeration defaultmovingstate This is your choice

Your movingstate interface now only needs the getters displayed in the movestate There are two methods

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>