[英]How can I pass an object onto another class's method in my java code?
问题
如何在java中将对象传递给另一个类的方法? 当我从 class2 中的 class1 代码调用方法时,我的雀类机器人第二次连接。 正如您在控制台中看到的那样,机器人在开始调用该方法时会说“连接到雀”。 这会继续进入无限循环,并且不会执行我想要对机器人执行的操作(使其变为蓝色)。 我想知道如何将对象传递给另一个类方法来解决这个问题? 下面我得到了一个有用的提示。
我得到的有用提示
“出于某种原因,您将 Finch 初始化两次。基本上,您需要做的是将 Finch 对象放入您的方法的构造函数中,而不是再次初始化它”
安慰
第 1 类代码
package class1;
import java.util.Scanner;
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
import java.awt.Color;
public class class1 {
public static Finch red = new Finch();
public static void main(String[] args) {
red.setLED(Color.red);
System.out.println("eedde");
System.out.println("xssccsccscdcddcdccdcdcdcdc");
System.out.println("eedde");
System.out.println("eedde");
System.out.println("eedde");
class2.class2test(); // this works the method is called but it's the robot in class2 that's the issue.
}
}
2 类代码
package class2;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import edu.cmu.ri.createlab.terk.robot.finch.Finch;
public class class2 {
public static Finch red = new Finch(); //I will need to remove this when passing the object through
public static void main(String[] args) {
red.setLED(Color.red);
}
public static void class2test() {
System.out.println("CLASS2");
red.setLED(Color.blue); //this doesn't get executed
}
}
首先,出于某种原因,您有两个main
方法,除非您只是使用它们来测试Class
或其他东西,否则这不是必需的。 main
是程序将开始的地方。 每次运行该程序时,它只会开始一次,因此通常不需要两次。
要回答您的问题,要将Object
传递给方法,您只需将其添加到方法的参数中(在括号之间):
public static void class2test(Finch red) {
System.out.println("CLASS2");
red.setLED(Color.blue);
}
请注意它现在如何需要将Finch
传递给它才能被调用,它将命名为red
以在方法中使用。 您还可以删除public static Finch red = new Finch();
现在在class2
,因为现在不需要它。
现在这里有一个类似于您的示例main
来展示您如何调用该方法:
public class class1 {
public static Finch red = new Finch();
public static void main(String[] args) {
class2.class2test(red);
}
}
注意您现在需要如何将red
放在括号内,以便将您创建的Finch
作为类变量传递。 请注意,您在使用的名称class1
不需要匹配的方法参数的名称class2
。
无关注意 - 我还建议您查找正确的 Java 命名约定,您应该将类命名为WithCasingLikeThis
,而不是使用小写字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.