[英]Why can't I access the data field of Point2D in Java?
I want to create an array of 100 random points using Point2D.我想使用 Point2D 创建一个包含 100 个随机点的数组。 But why can't I access its data field while the data field of Point2D is public?
但是为什么我不能访问它的数据字段而 Point2D 的数据字段是公开的? It said "x cannot be resolved or not a field."
它说“x 无法解析或不是字段”。
public static void main(String[] args) {
Point2D[] points = new Point2D.Double[100];
for (int i = 0; i < points.length; i++) {
points[i] = new Point2D.Double();
points[i].x = Math.random() * 100;
points[i].y = Math.random() * 100;
}
}
You might want to use setLocation .您可能想要使用setLocation 。 The error-message just says that the compiler doesn't know what .x is supposed to mean on an object of type Point2D.
错误消息只是说编译器不知道 .x 在 Point2D 类型的对象上应该意味着什么。
In your code, points
has type Point2D[]
, therefore points[i]
has type Point2D
.在您的代码中,
points
类型为Point2D[]
,因此points[i]
类型为Point2D
。 Point2D
does not have members named x
or y
. Point2D
没有名为x
或y
成员。 The fact that at runtime the class of points[i]
happens to be Point2D.Double
, which does have such members, is irrelevant to the compiler's analysis.在运行时,
points[i]
的类恰好是Point2D.Double
,它确实有这样的成员,这一事实与编译器的分析无关。
You could instead declare points
as您可以改为将
points
声明为
Point2D.Double[] points = new Point2D.Double[100];
, or you could use Point2D.setLocation()
instead of assigning to member variables, as your other answer already suggests. ,或者您可以使用
Point2D.setLocation()
而不是分配给成员变量,正如您的其他答案已经建议的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.