When to use them?
I picked up on Java pretty quick, I took a class in high school.
But the teacher didn't go over this well enough for me to actually know.
Anyway I can ask for basic examples to go along with the answer so I have a 'visual' understanding.
Thank you.
public vs. private
Page 1 of 111 Replies - 507 Views - Last Post: 13 September 2011 - 08:40 PM
Topic Sponsor:
Replies To: public vs. private
#2
Re: public vs. private
Posted 13 September 2011 - 07:12 AM
Public means that the item (method or property) can be seen from another class.
Private means that it can be seen only from within the class it was made in.
In general you want everything to be private unless you have a valid and specific reason for another class to see it.
MSDN explanation of access modifiers
Private means that it can be seen only from within the class it was made in.
In general you want everything to be private unless you have a valid and specific reason for another class to see it.
MSDN explanation of access modifiers
#3
Re: public vs. private
Posted 13 September 2011 - 07:25 AM
Ok, thank you. That helps a lot. A "+" for you.
#4
Re: public vs. private
Posted 13 September 2011 - 07:31 AM

POPULAR
Public and private are two of the four access modifiers available in java. I'll stick to their use in class members here. They are the two extreme ends - the other two will come in handy when you start doing more with inheritance and packages, but we'll leave them aside for now.
Applied to a class field, "public" means "every object that can see this object can read this field's value and change it". "Private" means "no other class can see this field's value or change it." Put simply, the first rule is "fields should be private".
The reason for this is that if another class changes this field's value, you have no way of ensuring that the value is a legitimate one. Suppose you have an object on a plane, and it has a "position" represented by two ints, x and y. If your grid is 100X100, it wouldn't mean anything to have a negative value, or a value of 3,987,453 for either of those fields, but you have no way of making sure that those constraints are managed if the field is public. So you make fields private and if you want to allow someone to read them, you provide a getX() method. (but you want to think carefully about why you'd want someone else to look at that data - there can be good reasons, but most of the time there's no reason). If you want someone else to put this object somewhere on the grid, you can allow them to setX(), and in that method you check that the value is a reasonable one. Be aware, though, that simply setting values is seldom good design unless you're initializing a class. More often you want to do something to the object, not to its representation.
So instead of setX(97) you might prefer to ask the object to move(5,0): change your position by 5 in the x direction and 0 in the y direction, if you can. Or better, you might ask the object to accelerate(5,3): try to change your velocity by that vector.
This gives you more opportunity to define the object's behavior in the object itself, and to interact with the object on its own terms.
For another example, if you have a "Library" class, you would prefer to "check out" a book rather than setBorrower("jon").
The second part of the rule is an exception:
all fields should be private unless they are final and immutable
If you make a field final, its value cannot be changed. For primitives (int, float, etc) this means exactly what it sounds like: final int i = 56 means i is always 56, forever and ever, world without end.
This is not the case for objects, generally. This is because an object is actually a reference to a reference. When you declare final StringBuffer sb; you have a reference to a spot in memory which points to a StringBuffer object. The reference to the spot in memory cannot be changed: it always points to the same place. However, you can still do sb.append("I've changed the final sb!!!") and it'll work fine. That is, you can call all of an object's methods, including any that change its value, and they'll work, even if the object itself is final.
Some objects are "immutable": they provide no means for changing their value.
final String warning = "Danger! Danger!"; will always contain just exactly that text, because there's no method of the String class that allows you to change it.
So you can finalize constant strings, like warning messages, and know that they'll remain constant. That means you can safely make them public, since there's no way they can be changed out from under you.
Methods:
private methods can only be called by the object to which they belong. Public methods can be called by any object which has a reference to the object to which they belong, or by any object which knows about the class if the method is static.
My rule here is to start with the public methods that define the object's behavior, and then make any "helper methods" which are required to facilitate the public methods private.
So if I have a public void setX(int newX) method for setting an X coordinate, I might decide to sub out the validity checking to another method. I'll make that pivate:
private boolean validateX(int newX)
Checking whether a given int is a valid value for x is not something I want to expose to the other classes: I don't want them to start depending on it, I want to be able to change it or eliminate it, so I make it private and only give them the access that I'm willing to maintain.
That's a sort of an overview, but it'll get you started on the subject.
Applied to a class field, "public" means "every object that can see this object can read this field's value and change it". "Private" means "no other class can see this field's value or change it." Put simply, the first rule is "fields should be private".
The reason for this is that if another class changes this field's value, you have no way of ensuring that the value is a legitimate one. Suppose you have an object on a plane, and it has a "position" represented by two ints, x and y. If your grid is 100X100, it wouldn't mean anything to have a negative value, or a value of 3,987,453 for either of those fields, but you have no way of making sure that those constraints are managed if the field is public. So you make fields private and if you want to allow someone to read them, you provide a getX() method. (but you want to think carefully about why you'd want someone else to look at that data - there can be good reasons, but most of the time there's no reason). If you want someone else to put this object somewhere on the grid, you can allow them to setX(), and in that method you check that the value is a reasonable one. Be aware, though, that simply setting values is seldom good design unless you're initializing a class. More often you want to do something to the object, not to its representation.
So instead of setX(97) you might prefer to ask the object to move(5,0): change your position by 5 in the x direction and 0 in the y direction, if you can. Or better, you might ask the object to accelerate(5,3): try to change your velocity by that vector.
This gives you more opportunity to define the object's behavior in the object itself, and to interact with the object on its own terms.
For another example, if you have a "Library" class, you would prefer to "check out" a book rather than setBorrower("jon").
The second part of the rule is an exception:
all fields should be private unless they are final and immutable
If you make a field final, its value cannot be changed. For primitives (int, float, etc) this means exactly what it sounds like: final int i = 56 means i is always 56, forever and ever, world without end.
This is not the case for objects, generally. This is because an object is actually a reference to a reference. When you declare final StringBuffer sb; you have a reference to a spot in memory which points to a StringBuffer object. The reference to the spot in memory cannot be changed: it always points to the same place. However, you can still do sb.append("I've changed the final sb!!!") and it'll work fine. That is, you can call all of an object's methods, including any that change its value, and they'll work, even if the object itself is final.
Some objects are "immutable": they provide no means for changing their value.
final String warning = "Danger! Danger!"; will always contain just exactly that text, because there's no method of the String class that allows you to change it.
So you can finalize constant strings, like warning messages, and know that they'll remain constant. That means you can safely make them public, since there's no way they can be changed out from under you.
Methods:
private methods can only be called by the object to which they belong. Public methods can be called by any object which has a reference to the object to which they belong, or by any object which knows about the class if the method is static.
My rule here is to start with the public methods that define the object's behavior, and then make any "helper methods" which are required to facilitate the public methods private.
So if I have a public void setX(int newX) method for setting an X coordinate, I might decide to sub out the validity checking to another method. I'll make that pivate:
private boolean validateX(int newX)
Checking whether a given int is a valid value for x is not something I want to expose to the other classes: I don't want them to start depending on it, I want to be able to change it or eliminate it, so I make it private and only give them the access that I'm willing to maintain.
That's a sort of an overview, but it'll get you started on the subject.
#5
Re: public vs. private
Posted 13 September 2011 - 10:55 AM
Thank you jon.kiparsky, knowing the few pages of notes I already have and already knowing roughly how much more I need to do... I need more than public and private.
Do you think you can go over the other 2 I didn't ask about in another post and link it in this one?
Thanks again.
Do you think you can go over the other 2 I didn't ask about in another post and link it in this one?
Thanks again.
#6
Re: public vs. private
Posted 13 September 2011 - 11:07 AM
You were given a link to the entire explanation on MSDN.
What about that explanation did you not grasp?
Why is it you think you need something other than public or private? Because honestly, I don't see rookies who really need more than that for quite a long time. At this point you shouldn't be building anything from scratch. You should be concentrating on learning from tutorials and books and lessons: Not trying to design and build your own applications.
What about that explanation did you not grasp?
Why is it you think you need something other than public or private? Because honestly, I don't see rookies who really need more than that for quite a long time. At this point you shouldn't be building anything from scratch. You should be concentrating on learning from tutorials and books and lessons: Not trying to design and build your own applications.
#7
Re: public vs. private
Posted 13 September 2011 - 11:17 AM
Read the Sunacle explanation of access modifiers - if you still have questions, feel free.
But if the questions are about "how does inheritance work" and "how do packages work" you should be aware that I'm pretty busy today, so I'm going to send you off to read the very good explanations that Sunacle already provides...
Specific questions, on the other hand, I'll have a go at.
But if the questions are about "how does inheritance work" and "how do packages work" you should be aware that I'm pretty busy today, so I'm going to send you off to read the very good explanations that Sunacle already provides...
#8
Re: public vs. private
Posted 13 September 2011 - 11:26 AM
Down marking my question doesn't really answer it.
Why do you think you need something other than public and private?
What is it you are working on?
What are you trying to accomplish/design and what are the requirements where neither public nor private will suffice?
Why do you think you need something other than public and private?
What is it you are working on?
What are you trying to accomplish/design and what are the requirements where neither public nor private will suffice?
#9
Re: public vs. private
Posted 13 September 2011 - 11:34 AM
Dude, the guy's a Klingon. Down-repping could be hazardous. Don't they have some sort of thing where if you besmirch their honor, they come after you and cut off your head and feed it to you? 
(on the other hand, I can see how an MSDN explanation might seem a little off the mark for a Java developer... Java has good documentation, we don't need no steenkin' MicroLimp)
(on the other hand, I can see how an MSDN explanation might seem a little off the mark for a Java developer... Java has good documentation, we don't need no steenkin' MicroLimp)
This post has been edited by jon.kiparsky: 13 September 2011 - 11:36 AM
#10
Re: public vs. private
Posted 13 September 2011 - 11:49 AM
Good point about the MSDN and java. Though I think the uses of the access modifiers is fairly close/in-line with each other. Probably not perfectly, but I knew where to find those as a start to someone's learning.
I commonly ask why someone thinks they need x,y or z - especially if they are a new to coding. So many times their limited exposure to coding means they only know about a, b and c but not F, G or H which would make it far easier to reach their end goal. So finding out their *goal* and not their *plan* will often help suggest something better and new to the OP.
And if I can't answer it because of my unfamiliarity with the topic, it has gotten the information out there so the next guy who does know about it get prompted to pick up the conversation and help out.
In this case I think the OP just got personally offended at the idea they should be learning more and might not yet be ready to design their own application from scratch. Oh well. He's young. Kids react a certain way. I'm sure I did the same sort of things when I was his age too. (Though by 21 I was PFC and had a confirmed body-count to my service record) I'm not offended by it. I just write it off to youth and (as I have done) make a second effort to offer assistance. My how we mellow with the passing years.
I commonly ask why someone thinks they need x,y or z - especially if they are a new to coding. So many times their limited exposure to coding means they only know about a, b and c but not F, G or H which would make it far easier to reach their end goal. So finding out their *goal* and not their *plan* will often help suggest something better and new to the OP.
And if I can't answer it because of my unfamiliarity with the topic, it has gotten the information out there so the next guy who does know about it get prompted to pick up the conversation and help out.
In this case I think the OP just got personally offended at the idea they should be learning more and might not yet be ready to design their own application from scratch. Oh well. He's young. Kids react a certain way. I'm sure I did the same sort of things when I was his age too. (Though by 21 I was PFC and had a confirmed body-count to my service record) I'm not offended by it. I just write it off to youth and (as I have done) make a second effort to offer assistance. My how we mellow with the passing years.
#11
Re: public vs. private
Posted 13 September 2011 - 11:51 AM
@Viper2KX
Down voting a member simply because you don't exactly like what he says isn't necessarily a very good thing to do; let alone a mentor. He did not break any rules; he simply asked you what you are not understanding and gave his opinion on how it doesn't particularly matter about anything other than private and public for now. Seeing as how you should learn the basics before you jump into advanced situations like that. Still being a beginner in java, you wont be writing any real world applications where you need to implement things like that. Instead of down voting him, could you please take a minute and respond and tell us why you think that you need more than private and public member types?
@tlhIn`toq
I can see where he is coming from to an extent, he might want to know all of his options to know which member to appropriately use at the right times. I do agree with you in the sense that he shouldn't be getting too far ahead of himself. He does indeed need to learn to walk before he runs. I liked your statement
Down voting a member simply because you don't exactly like what he says isn't necessarily a very good thing to do; let alone a mentor. He did not break any rules; he simply asked you what you are not understanding and gave his opinion on how it doesn't particularly matter about anything other than private and public for now. Seeing as how you should learn the basics before you jump into advanced situations like that. Still being a beginner in java, you wont be writing any real world applications where you need to implement things like that. Instead of down voting him, could you please take a minute and respond and tell us why you think that you need more than private and public member types?
@tlhIn`toq
I can see where he is coming from to an extent, he might want to know all of his options to know which member to appropriately use at the right times. I do agree with you in the sense that he shouldn't be getting too far ahead of himself. He does indeed need to learn to walk before he runs. I liked your statement
This post has been edited by Fuzzyness: 13 September 2011 - 12:12 PM
#12
Re: public vs. private
Posted 13 September 2011 - 08:40 PM
tlhIn`toq, on 13 September 2011 - 10:12 AM, said:
Java has a lot of good explanations and tutorials too
Don't see what you have to imply Bill Gates here
Especially that Java does not have internal and defaults to protected while C++ defaults to private.
This post has been edited by pbl: 13 September 2011 - 08:54 PM
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote





|