Java 如何从子类访问主类的公共常量变量?
我有一个带有几个公共常量变量的主类,还有一个自定义类,我想知道如何从自定义类访问主类的常量 主要类别代码:Java 如何从子类访问主类的公共常量变量?,java,class,constants,processing,main,Java,Class,Constants,Processing,Main,我有一个带有几个公共常量变量的主类,还有一个自定义类,我想知道如何从自定义类访问主类的常量 主要类别代码: 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
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参考。例如,VoronoiTest.SITE_MAX_水平。使用PApplet引用时,编译器无法知道静态变量是否存在。静态字段通过类名访问。使用VoronoiTest.SITE\u MAX\u VEL你不能。由于
parent
的类型为PApplet
,而不是VoronoiTest
,因此无法保证它具有静态成员站点的最大级别
相反,如果parent
属于VoronoiTest
类型,则通过实例访问静态变量没有什么意义,因为它不可能更改
如前所述,要访问静态成员,请使用ClassName.static\u MEMBER
符号(在本例中为VoronoiTest.SITE\u MAX\u VEL
)
不过更好的是,只需将常量存储在站点
类中即可。毕竟,这似乎是他们最合乎逻辑的地方
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)
);
}
}
Site不是VoronoiTest的一个子类。