非法正向参考和枚举 [英] Illegal Forward Reference and Enums

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

问题描述

我在Java中编程一个游戏,它由一个瓦片组成。我不能无意地界定瓦片的边缘,以及它们如何相互关联,例如要得到一个瓦片的相对边缘,我想要能够输入 TOP.opposite()。然而,当使用枚举来定义这些边,我最终必须在构造函数中转发至少两个参考:

  public enum Edge {

TOP(Edge.BOTTOM),//非法转发参考
BOTTOM(Edge.TOP),
LEFT(Edge.RIGHT),//非法转发参考
RIGHT(Edge.LEFT);

私人边对面;

私人边缘(Edge opp){
this.opposite = opp;
}

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

有没有办法使用枚举来解决这个问题这是一样的简单?

解决方案

你可以做到这一点不直观。

  public enum Edge {
TOP,BOTTOM,LEFT,RIGHT;
私人边对面;

static {
TOP.opposite = BOTTOM;
BOTTOM.opposite = TOP;
LEFT.opposite = RIGHT;
RIGHT.opposite = LEFT;
}
public Edge对(){
return this.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天全站免登陆