首页 > 解决方案 > 从 Java 构造函数获取变量

问题描述

我是 Java 编程新手,如果这是一个愚蠢的问题,我很抱歉。

我发现这个问题很难正确表达,但我有一个任务是创建一个可以使飞机着陆、起飞等的飞机类。并且需要使用 Testclass 对其进行测试。当输入新对象时,它会在构造函数中自动为飞机分配一个唯一的 ID。

我可以使用实例方法很好地做到这一点,因为它有一个返回到 Testclass 的返回值。问题希望我在构造函数本身中执行此操作,但是构造函数从不返回任何内容。所以变量永远不会被发送到Testclass。我显然没有正确理解 OOP。即使我尝试仅使用一种getter方法来获取在构造函数中创建的 ID,它也会在构造函数处理此之前给我初始化变量。这是我到目前为止的代码,我知道它完全错误,但如果有人能指出我正确的方向或告诉我如何更好地表达这个问题,那将是一个巨大的帮助。

// I need to enter 3 aircraft into the system in the testclass

public class Aircraft {

  private int aircraftID;
  private static int lastID;
  private String airportcode;
  private int ID = 100;

  private int count;



  public Aircraft(int a, int b, int c){
    // Constructor


     // Assign ID
     this.ID = a;
     lastID = ID;
     ID++;

     this.ID =b;
     lastID = ID;
     ID++;
  }
}

标签: javaconstructor

解决方案


好的,您想创建一个具有自动分配的唯一标识符并且可以起飞和降落的飞机。这意味着您需要一个用于跟踪标识符的字段,一个用于跟踪它是否在空中(或不在)的字段,以及起飞和着陆操作的方法。您还需要一个静态字段来生成唯一标识符。(请注意,此实现不是线程安全的。)

private class Aircraft {

    private static int staticId = 0;
    private int uniqueId = 0;
    private boolean onGround = true; // Aircraft start on the ground in this implementation

    public Aircraft(){
        this.uniqueId = staticId; // putting this line first makes uniqueId zero-indexed in effect
        staticId++;
    }

    public void land(){
        onGround = true;
    }

    public void takeoff(){
        onGround = false;
    }

    public boolean isFlying(){
        return !onGround; // If it's not on the ground, it's flying
    }

    public int getUniqueId(){
        return uniqueId;
    }
}

单元测试检查相关类的所有方法和预期功能:

import org.junit.Test;
import static org.junit.Assert.*;
import Aircraft;

class Testclass {

    private final Aircraft aircraft = new Aircraft();

    @Test
    public void hasId(){
        aircraft.getUniqueId() >= 0;
    }

    @Test
    public void canLand(){
        assertTrue(aircraft.land());
    }

    @Test
    public void canTakeOff(){
        assertTrue(aircraft.takeOff());
    }

    @Test
    public void checkFlightOperationsAreTrackedCorrectly(){
        aircraft.land();
        assertFalse(aircraft.isFlying());
        aircraft.takeOff();
        assertTrue(aircraft.isFlying());
    }
}

推荐阅读