非法前向引用和枚举 [英] Illegal Forward Reference and Enums

查看:44
本文介绍了非法前向引用和枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 编写一个由瓷砖网格组成的游戏.我不想能够直观地定义瓷砖的边缘以及它们如何相互关联,例如为了获得瓷砖的对边,我希望能够只输入 TOP.opposite().但是,当使用枚举定义这些边时,我最终不得不在构造函数中前向引用其中至少两个:

I'm programming a game in java which is made up of a grid of tiles. I wan't to be able to inuitively define the edges of the tiles and how they relate to each other, e.g. to get the opposite edge of a tile, I want to be able to just type TOP.opposite(). However, when using enums to define these edges I end up having to forward reference at least two of them in the contstructor:

public enum Edge {

   TOP(Edge.BOTTOM), //illegal forward reference
   BOTTOM(Edge.TOP),
   LEFT(Edge.RIGHT), //illegal forward reference
   RIGHT(Edge.LEFT);

   private Edge opposite;

   private Edge(Edge opp){
      this.opposite = opp;
   }

   public Edge opposite(){
      return this.opposite;
   }
}

有没有什么方法可以使用同样简单的枚举来解决这个问题?

Is there any way of getting round this problem using enums which is just as simple?

推荐答案

您可以这样做,但不是很直观.

You can do this which is not as intuitive.

public enum Edge {
    TOP, BOTTOM, LEFT, RIGHT;
    private Edge opposite;

    static {
        TOP.opposite = BOTTOM;
        BOTTOM.opposite = TOP;
        LEFT.opposite = RIGHT;
        RIGHT.opposite = LEFT;
    }
    public Edge opposite(){
        return this.opposite;
    }
}

这篇关于非法前向引用和枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆