[英]Accessing objects from another class in java?
i know that this question has been asked many types, but i am not getting trough the problem. 我知道这个问题已经问了很多类型,但是我并没有解决这个问题。 So following.
所以下面。 I have created a class that is creating array of 2 positions.
我创建了一个创建2个位置数组的类。 The goal is to create point coordinates so i can generate several points later.
目标是创建点坐标,以便以后可以生成多个点。 Hier is my code
嗨是我的代码
import java.util.Random;
public class Coor {
private static int[] coord;
public static int[] generate(){
coord = new int[2];
return coord;
}
public static void printX(){
System.out.println("X = " + coord[0] );
}
public static void printY(){
System.out.println("Y = " + coord[1] );
}
public static int randomFill(){
Random rand = new Random();
int randomNum = rand.nextInt(99);
return randomNum;
}
public static void main(String args[]) {
generate();
for(int i = 0; i < 2; i++){
coord[i] = randomFill();
}
printX();
printY();
}
}
So, this is working perfect, but what I want is to create the points in another class and to use them there, but I have no idea how to achieve this. 因此,这很完美,但是我想要在另一个类中创建这些点并在其中使用它们,但是我不知道如何实现这一点。 I am new to java, and I have almost understood some examples in the oracle docs, but can not implement it.
我是Java的新手,我几乎了解oracle docs中的一些示例,但是无法实现。 Can you please help me a little?
你能帮我一下吗? I just need one example class which is obtaining the coordinates of the points, after that I can extend it alone for my needs.
我只需要一个示例类来获取点的坐标,之后我就可以根据需要单独扩展它。
You should not make your data static and you should provide a public constructor see below. 您不应将数据设为静态,而应提供一个公共构造函数,请参见下文。
public class Coord {
private int[] coord;
public Coord(int x, int y) {
coord = new int[2];
coord[0] = x;
coord[1] = y;
}
public void printX(){
System.out.println("X = " + coord[0] );
}
public void printY(){
System.out.println("Y = " + coord[1] );
}
public static void main(String[] args) {
Coord c1 = new Coord(10, 11);
Coord c2 = new Coord(23, 14);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.