java一个类中的变量的值赋值给另一个类中的变量,供后面类处理,最好有例子

如题所述

package chn1; //类1
import java.util.Random;
public class ReadRandom extends Thread{
private Random ran = new Random();
private double []random; //定义数组变量
public void run(){
random = new double[1000];
for(int i = 0;i < random.length;i++){ //初始化变量
random[i] = ran.nextDouble();
// System.out.println(random[i]);
}
}
public String getRandom(){ //get()方法确保另一个类能够使用该变量
run();
String str = "";
for (int i = 0; i < random.length; i++) {
str += random[i] + "\n";
}
return str;
}
}

package chn1; //类2
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteRandom extends Thread{
ReadRandom rr = new ReadRandom(); //类1创建实例
File file;
public void run(){
String string = rr.getRandom(); //类2通过get()方法得到类1的数组变量
System.out.println(string);
file = new File("E:\\","Example.txt");
try{
if(!file.exists()){
file.createNewFile();
}
FileWriter fWriter = new FileWriter(file);
fWriter.write(string);
fWriter.close();
}
catch (IOException e) {
// TODO: handle exception
}
}

public static void main(String[] args) {
ReadRandom rr = new ReadRandom();
WriteRandom wr = new WriteRandom();
rr.start();
wr.start();
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-12-09
1.可以将变量声明为public static 类型的,这样就可以在后续的类中直接使用类名直接引用了;
2.可以使用单例模式:
public class Singleton(){
private String a;
private Singleton(){ }
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
public void setA(String b){
this.a = b;
}
public String getA(){
return a;
}
}
然后后面的类就可以通过Singleton.getInstance.setA(String b)来对变量a设置值,然后用Singleton.getInstance.getA()来获取a的值本回答被提问者采纳
相似回答