k9yosh
k9yosh

Reputation: 878

What is the best way to create objects from several classes and insert values?

I have a class called Features that looks like this,

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;
    }
}

And i have another called Camera like this,

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;
    }
}

And i'm trying to create a phone using these two classes in a class called Phone. How do i do this and pass the values?

Upvotes: 1

Views: 63

Answers (2)

Edi G.
Edi G.

Reputation: 2420

ehm... the "same" way like Camera and Features ... :)

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;
    }

}

then... new Phone(new Camera(....), new Features(...) ...

and your homework is finished.. :P

Upvotes: 3

Mustafa sabir
Mustafa sabir

Reputation: 4360

Your Phone class can contain Features and Camera , then you can use setters or constructor to set values for those fields:-

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;
}

}

There is also a typo in your source, remove the extra , from the contructor parameters of Features

Upvotes: 1

Related Questions