从多个类创建对象并插入值的最佳方法是什么?

时间:2014-09-01 06:30:00

标签: java oop

我有一个名为功能的课程,如下所示,

public class Features {
    public String opSys;
    public String chipset;
    public String cpu;
    public String gpu;

    public Features(String opSys,String chipset,String cpu,String gpu,) {
        this.opSys = opSys;
        this.chipset = chipset;
        this.cpu = cpu;
        this.gpu = gpu;
    }
}

我还有另一个名为相机的照片,

public class Camera {
    public String primary;
    public String features;
    public String video;
    public String secondary;

    public Camera(String primary, String features, String video, String secondary){
        this.primary = primary;
        this.features = features;
        this.video = video;
        this.secondary = secondary;
    }
}

我正试图在名为手机的课程中使用这两个课程制作手机。我该怎么做并传递值?

2 个答案:

答案 0 :(得分:3)

嗯..."相同"像CameraFeatures ... :)

这样的方式
public class Phone {
    private Camera camera;
    private Features features;

    public Phone(Camera camera, Features features){
        this.camera = camera;
        this.features = features;
    }

    public void setCamera(Camera newCamera){
        this.camera = newCamera;
    }

    public void setFeatures(Features newFeatures){
        this.features = newFeatures;
    }

    public Camera getCamera(){
        return camera;
    }

    public Features getFeatures(){
        return features;
    }

}

然后...... new Phone(new Camera(....), new Features(...) ...

你的作业已经完成..:P

答案 1 :(得分:1)

您的电话类可以包含FeaturesCamera,然后您可以使用setter或构造函数为这些字段设置值: -

class Phone{

private Camera camera;
private Features features;

//use constructor to set values

public Phone(Camera camera, Features features){
this.camera=camera;
this.features= features
}

public Phone(String opSys, String chipset, String cpu, String gpu, String primary, String features, String video, String secondary){
camera=new Camera(opSys, chipset, cpu, gpu);
features= new Features(primary,features, video, secondary);
}

//or use setters to set value

public setCamera(Camera camera){
// set values
this.camera=camera;
}

public setFeatures(Features features){
//set values
this.features=features;
}

}

您的来源中还有一个拼写错误,请从,的构造函数参数中删除额外的Features