Trouble using aggregate classes
Hey everyone, I'm pretty new with Java and am preparing for a class I'm taking later this summer. I've been doing a lot of self study and have been attempting to get as far as I can in some Java books by myself. Right now I'm working on a carpet calculator problem and I'm a bit stuck. I'm attempting to create a RoomDimension class to set the area of a room, then use a method from that class to establish an argument in a RoomCarpet class which calculates the total cost of of carpeting for the room.
Code Java:
public class RoomCarpet {
private double carpetCost;
private double roomSize;
private RoomDimension yourSize;
// This is what I'm having trouble with
public RoomCarpet(double cost, double roomsize){ // I'm not sure if I should use double or a RoomDimension object as the parameter
carpetCost = cost;
yourSize = new RoomDimension(); // I'm not sure what to pass as arguments here
roomSize = yourSize.getArea();
}
...
and here's the RoomDimension class:
Code Java:
public class RoomDimension {
private double length;
private double width;
public RoomDimension(double len, double w){
length = len;
width = w;
}
public RoomDimension(RoomDimension object2){
length = object2.length;
width = object2.width;
}
public double getArea(){
return length * width;
}
public String toString(){
String str;
str = "This rooms area is " + getArea();
return str;
}
}
I'd appreciate any help I can get. Thanks!
Re: Trouble using aggregate classes
You could always have both.
Create a second one that will initialize your current object to the values of the parameter object.
Use getters and setters, like setLength(), setWidth(), setCost(), etc. You do need a RoomDimension constructor with 0 arguments in order to do that. By default it makes one if there none but doesn't if there are any others.
Code java:
public RoomCarpet(double cost, double roomsize){ // I'm not sure if I should use double or a RoomDimension object as the parameter
carpetCost = cost;
yourSize = new RoomDimension(); // I'm not sure what to pass as arguments here
roomSize = yourSize.getArea(); // Why are you doing that? You're changing the parameter's value?
}
public void setCost(double cost)
{
carpetCost = cost;
}
public double getCost()
{
return carpetCost;
}
public void setRoomSize(double roomSize)
{
this.roomSize = roomSize; // this refers to the RoomCarpet object itself
}
public double getRoomSize()
{
return roomSize;
}
public RoomCarpet(RoomCarpet rc)
{
setCost(rc.getCost());
setRoomSize(rc.getRoomSize());
}
Re: Trouble using aggregate classes
this is inheritance or not ?
Re: Trouble using aggregate classes
No it's not inheritance. If anything, it's composition (or aggregation) hence the thread title.