java - 如何在我的 java 代码中将对象传递给另一个类的方法?
问题描述
问题
如何将一个对象传递给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
只是程序开始的地方。每次运行程序时,它只会开始一次,因此通常不需要两次。
要回答您的问题,要将 an 传递Object
给方法,您只需将其添加到方法的参数中(括号之间):
public static void class2test(Finch red) {
System.out.println("CLASS2");
red.setLED(Color.blue);
}
请注意它现在如何需要将 aFinch
传递给它才能被调用,它将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
,而不是使用小写字母。
推荐阅读
- node.js - Node.js 如何知道我安装了某个包?
- python - 归一化和绘制按第 4 列分组的 3 列数据
- firebase - firebase 删除文档会在控制台中删除其子集合?
- c++ - 我的部分代码作为我的 if 语句的一部分被跳过
- python - 在 DataFrame 集合上使用多处理
- python - Encoder.encode 与转储(cle=Encoder)
- python - 在 Chrome 或 Edge 中,大数据框中的所有行都不会显示 pandas 样式
- javascript - Fabric JS 使用 canvas.toJSON() 和 canvas.loadFromJSON() 在较小但相同的图像上复制图像编辑步骤
- java - 针对不同类型实体的微服务设计
- joomla - 试图输出变量(可能是对象)的键和值,但它什么也不输出