簡體   English   中英

在另一個類中使用主類的對象

[英]Using an object from main class in another class

因此,我們正在嘗試創建一個AI機器人,但我發現Java並不像我想的那么簡單。 我想做的是從另一個類中獲取一個對象。

主班:

    package main;


   import lejos.hardware.Brick;
   import lejos.hardware.BrickFinder;
   import lejos.hardware.motor.EV3LargeRegulatedMotor;
   import lejos.robotics.RegulatedMotor;
   import movement.Forward;

   public final class Runner {


    public static void main(String[] args) {
        //create brick
        Brick brick = BrickFinder.getDefault();

        // create motors
        RegulatedMotor left = new EV3LargeRegulatedMotor(brick.getPort("A"));
        RegulatedMotor right = new EV3LargeRegulatedMotor(brick.getPort("D"));

        //initialize motors
        left.setAcceleration(400);
        right.setAcceleration(400);

        left.setSpeed(400);
        right.setSpeed(400);



    Forward forward = new Forward();
        forward.moveForward();

    }



}

但是另一個班級是這個

    package movement;


   import lejos.utility.Delay;
   import main.Runner;

   public class Forward{

    public int speed;



    public void moveForward(){
        //moves forward for 5 seconds, then floats until motor stops and then closes the motors
            left.backward();
            right.backward();

            Delay.msDelay(5000);

            left.flt();
            right.flt();

            left.close();
            right.close();



    }

}

我想使用左右對象來制作可以向前移動的方法。

您可以左右傳遞前進:

Forward forward = new Forward(left, right);

並更改正向構造函數:

public class Forward{

    public int speed;
    RegulatedMotor left;
    RegulatedMotor right;

    public Forward(RegulatedMotor l, RegulatedMotor r) {
        left = l;
        right = r;
    }

您的Forward類顯然需要引用兩個電機實例。 您應該在施工時轉發它們(不要雙關語):

public class Forward {
    private final RegulatedMotor left;
    private final RegulatedMotor right;

    public Forward(RegulatedMotor left, RegulatedMotor right) {
        this.left = left;
        this.right = right;
    }

    public void moveForward() { ... }
}

您的foward方法現在可以訪問它們。 現在必須按照以下步驟構造此類Forward

Forward forward = new Forward(left, right);

首先,您必須在“ main”子例程之外初始化它們。 然后,您必須將它們公開和靜態化。

public static RegulatedMotor left;
public static RegulatedMotor right;
public static void main(String[] args)
{
    left = new EV3LargeRegulatedMotor(brick.getPort("A"));
    right = new EV3LargeRegulatedMotor(brick.getPort("D"));
    //rest of code as normal.
}

然后從另一個類訪問它們,我相信您會使用:

Runner.left.Whateverfunction();

對於“左”對象;

Runner.right.Whateverfunction();

對於“正確”的對象。

因為我主要是C#程序員,所以可能會出現一些語法錯誤,但是我相信這應該或多或少是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM