如何在其他班级中引用班级

时间:2020-10-17 15:05:12

标签: java

所以我制作了一个带有两个输入(String,double)的wheel类:

public class Wheel
{
    private String name;
    private double radius;
    private double circumference =  2 * Math.PI * radius;

    /**
     * Constructor for objects of class Wheel
     */
    public Wheel(String name, double radius)
    {
       this.name = name;
       this.radius = radius;
    }
    /**
     * Accessor method for Circumference variable
     */
    public double getCircumference()
    {
        return circumference;
    }
    
}

我想在我的引擎类中引用它,

public class Engine
{
    // instance variables - replace the example below with your own
    private String[] name;
    private double tpl;
    private double totalNumTurns;
    private double distanceToTravel;
    Wheel wheel = new Wheel("Wichelin15", 15);

public double getDistanceToTravel()
    {
        this.distanceToTravel = wheel.getCircumference() * tpl;
        return distanceToTravel;
    }
}

但是我不想输入参数,因为这两个类将在另一个将同时输入两者参数的类中被引用。 有帮助吗?

1 个答案:

答案 0 :(得分:0)

您需要为Engine创建一个接受Wheel作为参数的构造函数。然后,您可以在管理对象初始化的类中使用此构造函数。例如:

class VehicleManager {
  Vehicle createVehicle(... you could put arguments here idk ...) {
    Wheel wheel = new Wheel(...);
    Engine engine = new Engine(wheel, ...);
    return new Vehicle(engine, ... other parts and attributes ...);
  }
}

这样,您就不必在Wheel类中对Engine对象进行硬编码。

看起来您在使用String[]作为引擎名称,而不只是String,是故意的吗?