spcial
spcial

Reputation: 1579

Access Parent Class in List

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

Answers (3)

Rais Alam
Rais Alam

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

JBarberU
JBarberU

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

osorio
osorio

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

Related Questions