How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define
getmethods to access these variables, andsetmethods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.For example, for a member variable:
You might have methods:
chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public
getmethod and keeping thesetprivate or not providing asetat all.