问题

如何在Java中将对象传递给另一个类的方法?当我从class2中的class1代码中调用一个方法时,我的雀科机器人将再次连接。正如您在控制台中看到的那样,机器人在调用方法开始时说“连接到雀科”。这样会不断循环,不会执行我想对机器人执行的操作(使其变为蓝色)。我想知道如何将一个对象传递到另一个类方法来解决此问题?下面我告诉了一个有用的提示。

有用的提示

“由于某种原因,您两次初始化了芬奇。基本上,您需要做的是在方法的构造函数中放置一个芬奇对象,而不是再次对其进行初始化。”

安慰

Console

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,而不要使用小写字母。

关于java - 如何在Java代码中将对象传递到另一个类的方法上?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59741476/

10-14 20:21
查看更多