Say you have a method in ClassA which returns a number based on a private variable, e.g.: //The Number variable private int myNumber; // skip code ... //The method public void returnMyNumber(){ return myNumber; } How would you go about accessing the number variable from ClassB? Something like: // Return classA variable public void returnClassAVariable(){ return ClassA.myNumber; } Any ideas?
Jack Weavesham
Greenhorn
Joined: Jan 10, 2003
Posts: 6
posted
0
& thinking about it, how could you test that the ClassA myNumber variable equals a ClassB variable?
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Originally posted by Jack Weavesham: Say you have a method in ClassA which returns a number based on a private variable, e.g.: //The Number variable private int myNumber; // skip code ... //The method public void returnMyNumber(){ return myNumber; } How would you go about accessing the number variable from ClassB? Something like: // Return classA variable public void returnClassAVariable(){ return ClassA.myNumber; } Any ideas?
As ClassA.myNumber is an *instance* variable, you can't access it without having an instance of ClassA. And once you had, you'd just use the getter method:
Notice though that this (especially the naming) seems to suggest a design problem: a classes interface should generally be about its behaviour, not about its internal data.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Originally posted by Jack Weavesham: & thinking about it, how could you test that the ClassA myNumber variable equals a ClassB variable?
Can you please give a more complete example of what you'd want to do - and why? Thanks!
Jack Weavesham
Greenhorn
Joined: Jan 10, 2003
Posts: 6
posted
0
The idea is just a sample class structure to learn from. As an overall idea : how could you add a private variable in ClassA (for example) to a private variable in ClassB?
Jasper Vader
Ranch Hand
Joined: Jan 10, 2003
Posts: 284
posted
0
so what you are wondering Jack, is how to assign what is returned to a variable in Class B, and somehow add that to a private variable, as an excersize? hmm interesting ps - i know it's just an excersize, but in terms of the tenets of OO programming and encapsulation, i think private variables are meant to not be shared around? of course, it would be possible. just an idea. [ January 11, 2003: Message edited by: Jasper Vader ]
giddee up
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.