我在调用另一个类的变量时遇到问题。假设我们有 class1 和 class2,而 class2 有一个类似的方法:
public Class2{
public void method2 (Element ele, Grammar utterance, String user) {
String speech =................
}
}
我的目的是获取这个“语音”变量并将其传递给 class1。关于如何做到这一点的任何想法?
你只需要在你的另一个 Class1 中有一个 Class2 的实例,所以例子是:
Class1 mySpeech = new Class1();
现在有权访问的对象mySpeech
可以访问作为语音包含的字符串变量是一个公共变量。
mySpeech.speech
但最好为此创建 getter/setter 方法,可以使用 eclipse 快捷方式创建:
Sources->Generate Getters and Setters
同样在命名一个类时,第一个字母使用大写并调用骆驼大小写约定。所以当你命名一个类时,调用它Class1
或ClassOne
.
您必须在提供字符串的对象中具有某种公共可见性。然后要么将字符串从第一个对象传递给第二个对象,要么通过引用将对象传递给第二个对象(不太推荐)。
public FirstClass {
private String speech = "I am the first object!";
public String getSpeech() {
return speech;
}
}
public SecondClass {
private string speechCopy;
public void takeSpeech(string speechCopy) {
this.speechCopy = speechCopy + " (not really, I'm a copy!)";
}
}
从这里,您只需调用方法来调用您想要的行为。您可以保留代码原样,但将 get/set 方法添加到每个对象,以便它们可以传递变量和引用。
您可以将 void method2(...) 更改为 public String method2(...) 并返回语音。然后在您的第一堂课中,您有一个 class2 的实例,调用 class2.method2(...) 将为类 1 提供语音变量
-在方法之前声明:公共静态字符串语音 -在方法或外部初始化:speech="hi" -从其他类调用(静态范围):Class1.speech