2011-04-02 122 views
1

我有一個主要的類有一些公共常量變量,我有一個自定義類,我想知道如何從自定義類訪問主類的常量?如何從子類訪問主類的公共常量變量?

主類代碼:

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));  
    } 
} 

任何幫助將非常感激!

+0

網站不是VoronoiTest的子類。 – 2011-04-02 12:12:10

回答

3

你不能。由於parent的類型爲PApplet,而不是VoronoiTest,因此無法保證其具有靜態成員SITE_MAX_VEL。

相反,如果parentVoronoiTest類型的,就不會有在通過實例訪問靜態變量小點,因爲這將是不可能的它改變。如上所述,要訪問靜態成員,請使用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) 
     );  
    } 
} 
0

使用VoronoiTest參考。例如,VoronoiTest.SITE_MAX_VEL。當您使用PApplet引用時,編譯器無法知道存在靜態變量。

0

靜態字段通過類名訪問。使用VoronoiTest.SITE_MAX_VEL