我在ReadSource类中设置了String消息,我想从Automotive类方法在Driver类中访问它,但是它显示的是null而不是消息。我试图在Automotive setName(String)中打印消息,它显示正确的String,但我无法在我的主类中访问它。
我的问题可以通过测试下面的代码来说明。
有人可以帮我解释一下吗?非常感谢你。
package Driver;
import Util.ReadSource;
import Model.Automotive;
public class Driver {
public static void main(String args[]){
Automotive auto = new Automotive();
ReadSource read = new ReadSource();
String main = "Message";
//set the message and display
read.set(main);
//get the message that was set in the read.set(String)
auto.getMessage();
}
}
package Util;
import Model.Automotive;
public class ReadSource {
public void set(String message){
Automotive auto = new Automotive();
System.out.println("This messasge is in getMessage in the
class ReadSource "+ message);
//Set the name for automotive
auto.setName(message);
}
}
//This the the ouput
/*This messasge is in getMessage in the class ReadSource Message
Message is Message
This messasge is in getMessage in the class Automotive null*/
答案 0 :(得分:1)
在ReadSource.set()方法中。您正在创建一个新的汽车实例。然后在创建一个新的Automotive实例(从未再次使用)之后,通过set方法再次传递消息的值。你想要做的是在类体的开头创建一个变量(在技术上是一个 field )。
public class ReadSource {
private String message;
public void setMessage(String message) {
this.message = message;
}
// make a getter to return it somewhere else
}
现在可以使用auto.getMessage()(或类似的东西)在主类中访问消息。
然后,如果在主要你是:
System.out.println(auto.getMessage());
它将打印传递给setMessage()方法的任何内容。
答案 1 :(得分:0)
public class Driver {
public static void main(String args[]){
Automotive auto = new Automotive();
ReadSource read = new ReadSource(auto);
String main = "Message";
//set the message and display
read.set(main);
//get the message that was set in the read.set(String)
auto.getMessage();
System.out.println(auto.getMessage());
}
public class ReadSource {
Automotive auto;
public ReadSource(Automotive auto) {
this.auto = auto;
}
public void set(String message) {
System.out.println("This messasge is in getMessage in the class ReadSource: " + message);
//Set the name for automotive
auto.setName(message);
}
}
public class Automotive {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return name;
}
}