【问题标题】:How to access public constant variables of main class from a sub class?如何从子类访问主类的公共常量变量?
【发布时间】:2011-04-02 11:46:54
【问题描述】:

我有一个包含几个公共常量变量的主类,我有一个自定义类,我想知道如何从自定义类访问主类的常量?

主类代码:

import processing.core.*;
import toxi.geom.*;
import toxi.math.*;

public class VoronoiTest extends PApplet {

    // this are the constants I want to access from the Site class
    public static int NUM_SITES         = 8;
    public static int SITE_MAX_VEL      = 2;
    public static int SITE_MARKER_SIZE  = 6;

    Site[] sites;

    public void setup() {
        size( 400, 400 );

        sites = new Site[NUM_SITES];
        for ( int i = 0; i < sites.length; i++) {
            sites[i] = new Site( this );
        }
    }
}

这是站点类代码:

import processing.core.*;


public class Site {
    PApplet parent;

    float x, y;
    PVector vel;

    int c;

    Site ( PApplet p ) {
            parent = p;
            // here I try to get the constants from the main class
            vel = new PVector( parent.random(-parent.SITE_MAX_VEL, SITE_MAX_VEL), parent.random(-SITE_MAX_VEL, SITE_MAX_VEL) );     
    }   
}

任何帮助将不胜感激!

【问题讨论】:

  • 站点不是 VoronoiTest 的子类。

标签: java class constants processing main


【解决方案1】:

你不能。因为parent 的类型是PApplet,而不是VoronoiTest,所以不能保证它具有静态成员SITE_MAX_VEL。

相反,如果parent 是 类型为VoronoiTest,则通过实例访问静态变量将毫无意义,因为它不可能更改。

如前所述,要访问静态成员,请使用ClassName.STATIC_MEMBER 表示法(在本例中为VoronoiTest.SITE_MAX_VEL)。

不过更好的是,只需将常量存储在 Site 类中即可。毕竟,这对他们来说似乎是最合乎逻辑的地方。

import processing.core.*;

public class Site {
    public static final int COUNT       = 8;
    public static final int MAX_VEL     = 2;
    public static final int MARKER_SIZE = 6;

    PApplet parent;

    float x, y;
    PVector vel;

    int c;

    Site(PApplet p) {
        parent = p;
        vel = new PVector(
            parent.random(-MAX_VEL, MAX_VEL),
            parent.random(-MAX_VEL, MAX_VEL)
        );     
    }   
}

【讨论】:

    【解决方案2】:

    使用 VoronoiTest 参考。例如,VoronoiTest.SITE_MAX_VEL。当您使用 PApplet 引用时,编译器无法知道静态变量是否存在。

    【讨论】:

      【解决方案3】:

      通过类名访问静态字段。使用VoronoiTest.SITE_MAX_VEL。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-04
        • 1970-01-01
        • 1970-01-01
        • 2012-04-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多