首页 > 解决方案 > 如何在我的 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
    }
}

标签: java

解决方案


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


推荐阅读