How can I use the created instance of B inside class C? I don't want to create a new B instance.
Is there a way to send the reference of the instance B to C? Is my way good or bad in terms of OO programming?
You said you are creating Instance of class B in Class A, but as I can see you are creating the Instances inside the main method so these objects are local to method and not Instance variables of the Class A.
you even not declare the variable "objectB" so how can you use that.
Do not wait to strike till the iron is hot; but make it hot by striking....
In which situation (how) can I access the class B in the class C then? I know that class A can access B with the getValue() method, because it has an reference to the instance B.
But with Class C which has no reference I don't know. Creating a new instance of class B in class C is not good because I like to access the only one class B I created.
Perhaps the following code will explain it why I like to do this.
- want to create a class ClockPanelDigital, want to seprate analog and digital clock panel
- my current class ClockPanelAnalog creates the ClockPanel, thus ClockPanelAnalog can call ClockPanel's method addPanel(object ClockPanelAnalog)
This adds the clockPanel to the clock frame. But how do I add another clockpanelDigital to the same ClockFrame?
- I have to let ClockPanelAnalog create the instance of ClockPanel, so that the TimeGenerator instance can add ClockPanelAnalog as an Observer.
You can pass these objects to other methods or, also other methods in other classes, or to constructors of other classes. You already have a complete program in which you're passing around objects all the time from method to method.
So surely you must already understand how to pass objects from one place to another, as arguments to a method or constructor. That's what you originally asked, but it's apparently not what your question is really about.
If you want to have one ClockFrame to which you add a ClockPanelAnalog and also a ClockPanelDigital, then you shouldn't put creating the ClockFrame in ClockPanelAnalog. You should probably create the ClockFrame in your main method, in class TimeGenerator, and then pass the ClockFrame object to the constructors of ClockPanelAnalog and ClockPanelDigital, which can then add themselves to the ClockFrame.
I was locked in my thinking, didn't know how to create the relationships between the objects so that it would work.
Forgot about the part that I could send an instance referance towards the constructor of another object. Doing so the new instance is able to use
the reference and so access it public methods.
(applying some more anti-rust.... joints are loosing up....)
A lot of people cry when they cut onions. The trick is not to form an emotional bond. This tiny ad told me:
Free, earth friendly heat - from the CodeRanch trailboss