【发布时间】:2014-02-21 19:50:23
【问题描述】:
我讨厌问这么琐碎的事情,但我无法解决这个问题。 为了方便起见,我正在尝试创建一个基本对象,如下所示:
triangle = {
side: { A: 0, B: 0, C: 0 },
angle: { a, b, c },
function calcAngle(){}
}
理想情况下,我只想动态创建一个通用对象。我只创建一个“三角形”,我必须为一个实例创建一个完整的类吗?我确信这在某个地方得到了回答,但我似乎无法正确地用任何有用的方式来表达这个问题。为了您的娱乐,我将发布我的一些失败:
public class TGUI{
// Attempt One
public Object triangle = new Object(){ int test; };
public static void main(String[] args) {
triangle.test = 1;
// ^- Cannot make a static reference to the non-static field triangle
triangle tri = new triangle();
// ^- Made the compiler cry; triangle cannot be resolved to as type
}
// Attempt Two
public class triangle{ int test; }
public static void main(String[] args) {
triangle tri = new triangle();
/* ^- No enclosing instance of TGUI is accessible. Must qualify the allocation with an enclosing instance of type TGUI (eg x.new A() where x is an instance of TGUI) */
}
// Attempt Three
public void triangle(){ int test = 1; }
public static void main(String[] args) {
triangle tri = new triantle();
// ^- triangle cannot be resolved to a type
}
// Attempt Four
public TGUI(){ int test; }
/* I'm gonna quit here, you get the idea */
}
【问题讨论】:
-
你可以使用一个包含三个
double值的数组吗? -
你需要定义一个三角形类。而且,一般来说,它应该不嵌套,除非你有充分的理由这样做。
-
我可以为边和角度制作单独的数组,但我喜欢 x.side.a 的组织; x.angle.b 而不是 side[0];角度[1];我想这就是要走的路。那么,正确的做法是在一个完整的单独文件中定义一个新类,只是为了使用该对象一次?也许地图就是要走的路。
-
您始终可以选择将其保留为 JSON 格式。您失去了能够在其上调用方法的“经典性”,但数据值仍然可以以相当有意义的方式访问。
标签: java class object constructor instance