Hello Yes, I know that subject is "C-ish", but please dont condemn me, grin. I have a class C that creates an instance of class B. Now class B has an instance variable of class A. From class C I want to get access to an member variable of class A. I am not extending the classes so they are not on the stack, but how do I get access to that "buried" variable? My trivial understanding is something like IWant = C.B.A.ThisVariable.
Get comfortable with making this work, then come back and ask why it might not be a good idea some times. I'm trying to tease you into getting interested in more advanced design ideas. Let us know how this goes.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Aug 27, 2005
Hi Stan Okay, so I was crudely right. From my reading the bad thing about this is that the instance variables are public and other classes can use them "behind my back". What I should do is make them private and proxy them with s/getters. How "deep" can I go with that "." referencing?
Originally posted by Stan James: Get comfortable with making this work, then come back and ask why it might not be a good idea some times. I'm trying to tease you into getting interested in more advanced design ideas. Let us know how this goes.
Any time class A needs to access a variable in a class B object it's holding, that's a sign that you've probably got a problem with your design: the code that you're writing in class A probably belongs in class B.
If you're writing code in A and you have a reference to B and B has a reference to C, and A needs a variable in C, then you don't "probably" have a flawed design: you absolutely have one. The code absolutely doesn't belong in A: it belongs either in B, or, ideally, in C.
And if you feel the need to type "A.B.C.D.x", then don't be surprised if the Java Police kick down your door and yell FREEZE!
>> From my reading the bad thing about this is that the instance variables are public and other classes can use them...
Yes, a long-standing C++ convention that is also used in Java. C++ has far better protection facilities such as declaring methods as immutable, having "protected" apply to sub-classes and not everything in the package, for example.
Joined: Jan 29, 2003
When I first learned OO and worked with some pretty cool Smalltalk experts long chains of variables were common. I don't know when people realized that every class suddenly knew a whole lot about a bunch of other classes and that made them all fragile - change one and the whole chain breaks. It's better to just ask an object to do something.
and let that object hide how it does it. For a humorous look at this, see Don't Confuse Your Dog near the bottom of that link.