The Artima Developer Community
Sponsored Link

Java Answers Forum
Setting Private Variables

1 reply on 1 page. Most recent reply: Mar 13, 2004 7:38 PM by twc

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Kevin

Posts: 25
Nickname: doublek321
Registered: Jan, 2004

Setting Private Variables Posted: Mar 13, 2004 4:20 PM
Reply to this message Reply
Advertisement
This is probably a dumb question but I have to ask it anyway...

What is the real benefit between having a method set a private variable (as in Example 1) vs the user setting the variable themselves (as in Example 2)? I know it's supposed to be better because "the private variable can only be accessed using my functions". However, what is the real tangible benefit here? The only thing I can think of is that example 1 gives you the flexibility to change the logic later on. Like, for example, you could set limits on what "myInt" can be set to (e.g. returning an error if the user tries to set it outside of a certain range). Is THAT the benefit that all the things I've read are talking about?

EXAMPLE 1
class myClass {
private int myInt;

public void setMyInt(int a) { myInt = a; }
public int getMyInt() { return myInt; }
}

EXAMPLE 2
class myClass {
public int myInt;
}


twc

Posts: 129
Nickname: twc
Registered: Feb, 2004

Re: Setting Private Variables Posted: Mar 13, 2004 7:38 PM
Reply to this message Reply
As you mentioned, validating data is a one reason - a big one in my mind.

Another is the situation where the value of one field may affect the value of others fields. For example, changing the "energy" level of a video game character might also affect its strength, speed or even size.

Perhaps the most important reason is that keeping variables private also prevents them from accidentally being overridden when a class is subclassed.

It is easy to overlook that when you are just learning since you typically are the only one using your code. But in a "real world" situation, it is common to be working with classes created by someone else. If a variable inadvertantly gets overridden by somebody that is subclassing it, the problems that result can be difficult to track down.

twc

Flat View: This topic has 1 reply on 1 page
Topic: exercise 11 Bruce Eckel chapter 4 Previous Topic   Next Topic Topic: Need Help Bad

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use