Reputation: 1579
I have following classes:
public class MeasurementUnit(){
...
private String name = "test";
private List<MeasurementPoint> measPoints;
...
}
and
public class MeasurementPoint(){
...
private String name = "subtest";
...
}
I'm doing some foreach
for creating tables or sometimes I have to give a certain MeasurementPoint
from measPoints
to a method... but is it somehow possible to access the name (or any other information) of the parent MeasurementUnit
from a certain MeasurementPoint
?
I think I could work with inheritance and extend MeasurementPoint
with MeasurementUnit
but then I would store the information twice, wouldn't I (in MeasurementUnit
and in the superclass of MeasurementPoint
)?
Is there maybe a better solution or idea for my problem?
Thanks in advance!
Upvotes: 0
Views: 65
Reputation: 7016
Object measPoints
is inside MeasurementUnit
class if you iterate measPoints
in class MeasurementUnit
then you can access every member of class MeasurementUnit
eg.
public class MeasurementUnit(){
...
private String name = "test";
private List<MeasurementPoint> measPoints;
for(MeasurementPoint measPoint:measPoints){
someOtherMethod(measPoint.getXXX(), measPoint.getYYYY(),name);
}
}
Upvotes: 1
Reputation: 1029
The inheritance solution sounds a bit weird to me.
I'd probably do something like:
public class MeasurementUnit(){
...
private String name = "test";
private List<MeasurementPoint> measPoints;
...
}
public class MeasurementPoint(){
...
private String name = "subtest";
private MeasurementUnit parent;
public MeasurementPoint(MeasurementUnit parent) {
this.parent = parent;
}
...
}
Upvotes: 0
Reputation: 71
You could create a getter for measPoints in MeasurementUnit, then add in MeasurementPoint's constructor a reference to your MeasurementUnit object and store it into an instance variable, and then reference this object every time you need to reference to measPoints.
Upvotes: 0