I have a "meter" class. One property of "meter" is another class called "production". I need to access to a property of meter class (power rating) from production class by reference. The powerRating is not known at the instantiation of Meter.
How can I do that ?
Thanks in advance
public class Meter { private int _powerRating = 0; private Production _production; public Meter() { _production = new Production(); } }
I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop. Show activity on this post. something like this: public int PowerRating { get { return base.
GetType(). BaseType returns the base Type of class o parent class. instance. GetType().
Java uses class-based inheritance. if you have B b = new B(); you can get the parent A by default casting Java provides. A a = (A)b This is automatic, so just writing A a = b will have the same result.
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
Store a reference to the meter instance as a member in Production:
public class Production { //The other members, properties etc... private Meter m; Production(Meter m) { this.m = m; } }
And then in the Meter-class:
public class Meter { private int _powerRating = 0; private Production _production; public Meter() { _production = new Production(this); } }
Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With