I am asking the user to input a value and then I am assigning the same to an attribute but, I want that change to be global. I searched on internet but yet I am not able to find the working solution for it. By the way I m using Java.
Thanx in advance.....
Java has class members for that. Also known as static fields.
This question has already been extensively covered. If you are looking on how to make a variable global/accessible from outside a class, check here.
However, if you are looking to make a global variable that can be accessed in and ONLY in a class, you can use the private static Keyword. Here is an example:
class myClass {
private static int myGlobalVariable; //Can only be accessed from methods in myClass
void changeMyVariable (int value) {
// Data validation here if needed
this.myGlobalVariable = value;
}
}
Related
I would like every object of a class be able to access a class variable but don't want to get modified outside class.
For example the way Array.length is used.
But would also like to have a method in class which conditionally modifies this variable.
Basically this usage is for a resizing object array implementation, where length of object array can change dynamically.
There seem to be a few confusing points here.
I would like every object of a class be able to access a class variable but don't want to get modified outside class. For example the way Array.length is used.
Array.length is (effectively) a final field - an array's length in Java cannot change, so it cannot be modified from inside or outside the class.
But would also like to have a method in class which conditionally modifies this variable.
If a variable is final, as the length field in array, then its value cannot be modified at all, by anything.
You're not going to get this level of control from a field directly. Instead you should follow the standard getter pattern - make the field private and non-final, provide a public method to get its value (getLength() for example) and then set it as you need to within that class. This gives you the flexibility to change the value from within the class as you need to, while still allowing the value to be read from anywhere else.
Array.length is marked final and hence cannot be modified after the constructor is returned. I don't know what you're talking about there.
I guess, you want a private field with public getters and private setters?
private int someField = 0;
public int getSomeField() { return someField; }
private void setSomeField(int newValue) {
if (someCondition) {
someField = newValue;
}
}
Since both someField and setSomeField are private, no code outside of this class can modify the value of someField.
Code outside can only get the value of someField.
Code inside the class can conditionally set the value of someField by calling setSomeField.
Requirements met!
I think what I was trying to do could be accomplished by ArrayList implementation. Thanks for your replies.
The title a little bit disappointing but I cannot figure out how to properly formulate the question.
So, I show my problem on the code.
For example we have:
public class Test {
public Value val;
Test(Value val){
this.val = val;
}
public static void main(String[] a){
Value val = new Value(1);
Test test1 = new Test(val);
val = new Value(2);
System.out.println(test1.val.val);
}
}
How can I change my code easily to let test1 point to the new Val (that that have the value of 2). Suppose the we need to have such references(to the actual variable and not the memory) all over the program
UPD: One of the solution I found is to make a "update" method. So I could write val.update(new Val(2))
UPD: I totally agree with the setter methods. What I want is not OOP style, but in my project I need a rapid solution even if it would not be the best. I think I found one solution(it is actually bad but faster then writing setters and getters. The solution is to create a "wrapper" class(I could name it "Reference")
Normally, you want to define a setter to change any of your field values in a class.
public void setVal(Value val) {
this.val = val;
}
But, since your val field is public, you don't have to use a setter at all.
// after you've declared `val` to be a new value
test1.val = val;
Setters are the convention when dealing with JavaBeans, or with frameworks that have an expectation that a field has a corresponding getter and/or setter.
Because we are supposed to give answers, I just will repeat what we got in the comments already.
To change the value of your instance variable Value val from the outside of the class, you have to write setter methods. If you want to retrieve the value, you need getter methods.
Bad practice: You should not declare the instance variable public and directly write it. This goes against OOP principles such as encapsulation aka you do not want to know what is done in the class, you just want to know its external behavior. So declare it private.
Also check Use public getters/setters to access private variables in the same class, or access the variables directly and http://www.cs.colostate.edu/~cs161/Fall12/labs/lab2/bookgetset.html
I have an integer(levelstatus) in class A(LevelSelectScene) and I want to change it in class B(GameScene), is it possible?
here is my code:
(Code in GameScene)
public class levelComplete()
{
levelSelectScene.getInstance.levelstatus=1;
}
LevelSelectScene has an public integer levelstatus.
and after an event happens, levelComplete will trigger and will change the value of levelstatus from null to 1.
Yes.
Make your levelstatus variable as static.
Because I guess you need to change that variable in each level class.
That means,you are wanting to access that variable through out the whole Game(All levels).
And also,Declare that variable in a Util class(proposing a name LevelUtil),Since it wont attach to a single level.
It is possible to change the value any where in the project(that is in any class) since the variable is declared as public levelstatus.
If you want to change the value of the variable in many places and the new value should be the modification of previously changed value, the you should declare the variable as public static levelstatus.
I believe it is more appropriate if you look into SharedPrefences of the Android API.
Check it here.
It could be used across the whole project of yours and it is handy in those kind of cases.
You can access your variable as a public static.
Definition:
public static Boolean isPremium;
Access (do not forget import) :
your_class.isPremium
I've read many large projects in OOP, and I notice that a lot of them use this.[variable], [ClassName].[staticVariable]. For example:
public class ABC {
private float mX;
public static float y;
public float getX() {
return this.mX;
}
public float doSomethingWithY() {
return ABC.y;
}
}
And even with Eclipse auto-generated Getters & Setters feature, it also comes with this.[variable], although it's unnecessary, because no local variable is declared there.
Is there any advantage when using these notations, or it's just a code style?
EDIT so some people don't misunderstand. I know what this and [ClassName].[staticVariable] stand for. But in this case, it's unnecessary. The question is: Even if it's unnecessary, why do guru coders still add it? When they need to update/fix a huge project, will there be any advantage and disadvantage?
Basically with this, you KNOW for sure that you are working with a class attribute, not with a variable created inside the method or maybe received as a parameter.
And also, it helps in case you have a local var with the same name.
And the final reason: readability.
It's necessary in some circumstances, for example this. is required when you need to use a member variable rather than a local method parameter of the same name.
It's also necessary for static variables where you need to be specific which class you want to get the static variable from (many classes could define static variables with the same name).
Apart from the necessary cases, it's really a matter of coding style. My recommendation is to use it whenever it helps to resolve potential ambiguity.
In complicated methods, it's sometimes nice to make a distinction between instance variables in this class, and local variables in a particular function. This distinction is immediately obvious when you use "this."
For small pieces of code it doesn't matter but sometimes this can happen:
public float getX() {
....
int mX = someFunc()
...
return mX;
}
In this case, the local value is returned instead of the member variable.
You normally want to be explicit and say this.mX. However, you shouldn't have huge functions anyway.
this.? '?' is a member variable, this is a reference to the current object.
see this
Its syntax,if you want to access instance variable of a class use the (reference of the object).(instance variable name) .Like
A a= new A();// for non static class,this for the current object
a.(instance variable name)
// for non static class do the same but use (class name).variable name
Ok, so I am about to embarrass my self here but I am working on a project that I will need to get some help on so I need to get some conventions down so I don't look too stupid. I have only been doing java for 2 months and 100% of that has been on Android.
I need some help understanding setting up variables and why I should do it a certain way.
Here is an example of my variables list for a class:
Button listen,feed;
Context context = this;
int totalSize = 0;
int downloadedSize = 0;
SeekBar seek;
String[] feedContent = new String[1000];
String[] feedItems = new String[1000];
ListView podcast_list = null;
HtmlGrabber html = new HtmlGrabber();
String pkg = "com.TwitForAndroid";
TextView progress = null;
long cp = 0;
long tp = 0;
String source = null;
String pageContent = null;
String pageName = "http://www.shanescode.com";
DataBaseHelper mdbHelper = new DataBaseHelper(this);
int songdur = 0;
So all of these are variables that I want to use in all through the whole class. Why would I make something a static, or a final. I understand Public but why make something private?
Thanks for your help and please don't be too harsh. I just need some clarification.
These words all alter the way the variable to which they are applied can be used in code.
static means that the variable will only be created once for the entire class, rather than one for each different instance of that class.
public class MyClass{
public static int myNumber;
}
In this case the variable is accessed as MyClass.myNumber, rather than through an instance of MyClass. Static variables are used when you want to store data about the class as a whole rather than about an individual instance.
final prevents the variable's value from changing after it is set the first time. It must be given an initial value either as part of its declaration:
public final int myNumber = 3;
or as part of the class's constructor:
public MyClass(int number){
this.myNumber = 3;
Once this is done, the variable's value cannot be changed. Keep in mind, though, that if the variable is storing an object this does not prevent the object's variable from being changed. This keyword is used to keep a piece of data constant, which can make writing code using that data much easier.
private modifies the visibility of the variable. A private variable can be accessed by the instance which contains it, but not outside that:
public class MyClass{
private int myNumber;
public void changeNumber(int number){
this.myNumber = number; //this works
}
}
MyClass myInstance = new MyClass();
myInstance.myNumber = 3; //This does not work
myInstance.changeNumber(3) //This works
Visibility is used to control how a class's variables can be used by other code. This is very important when writing code which will be used by other programmers, in order to control how they can access the internal structure of your classes. Public and private are actually only two of the four possible levels of visibility in Java: the others are protected and "no (visibility) modifier" (a.k.a not public or private or protected). The differences between these four levels is detailed here.
static = same for all instances of a class.
final = unchanging (reference) for a particular instance.
If you needed some field (aka a class variable) to be shared by all instances of a class (e.g., a constant) then you might make it static.
If you know some field is immutable (at least, it's reference is immutable) in an instance, then it is good practice to make it final. Again, constants would be a good example of a field to make final; anything that is constant within an instance from construction time on is also a good candidate for final.
A search for "java final static" gives pretty useful further reference on the use of those keywords.
The use of the private keyword controls what can accessed by other classes. I'd say it's biggest use is to help developers "do the right thing" - instead of accessing the internals of the implementation of another class, which could produce all sorts of unwanted behavior, it forces using accessor/mutator methods, which the class implementor can use to enforce the appropriate constraints.
Private
The idea behind using private is information hiding. Forget about software for a second; imagine a piece of hardware, like an X-Box or something. Somewhere on it, it has a little hatch to access the inside, usually sporting a sticker: "open this up and warranty is void."
Using private is sticking a sticker like that in your software component; some things are 'inside' only, and while it would be easy for anyone to open it up and play with the inside anyways, you're letting them know that if they do, you're not responsible for the unexpected behavior that results.
Static
The static keyword does not mean "same for all instances of a class"; that's a simplification. Rather, it is the antonym of "dynamic". Using the static keyword means "There is no dynamic dispatching on this member." This means that the compiler and not the run-time determines what code executes when you call this method.
Since thee are no instances of objects at compile-time this means that a static member has no access to an instance.
An example:
public class Cat {
public static void speak() { System.out.println("meow"); }
}
public class Lion extends Cat {
public static void speak() { System.out.println("ROAR"); }
}
// ...
public static void main(String argv[]) {
Cat c = new Lion();
c.speak();
}
The above prints "meow" - not "roar" - because speak is a static member, and the declared type of c is Cat, so the compiler builds in such a way that Cat.speak is executed, not Lion.speak. Were there dynamic dispatching on static members, then Lion.speak would execute, as the run-time type of c is Lion.
Another thing that might trip you up is this:
Not everything has to be a class level variable; you should have a variable defined for the smallest scope it needs to be defined.
So as an example, suppose your class only has one method which uses your TextView progress variable. Move that declaration into the method that needs it. This way it tidies things up and helps you make more robust code by separating out things that are really separate.
I don't know why you would make anything private.
Folks will chime in and say that private is a Very Important Thing.
Some folks will claim that you can't do encapsulation without private. Most of this seems to be privacy for privacy's sake.
If you are selling your code to someone else, then you must carefully separate the interface elements of your class from the implementation details of your class. In this case, you want to make the implementation private (or protected) so that -- for legal purposes -- the code you sell doesn't expose too much of the implementation details.
Otherwise, if you're not selling it, don't waste a lot of time on private.
Invest your time in separating Interface from Implementation. Document the Interface portions carefully to be sure you're playing by the rules. Clearly and cleanly keep the implementation details separate. Consider using private as a way to have the compiler "look over your shoulder" to be sure you've really separated interface from implementation.
One of the aspects of the object oriented approach that has made it so wildly popular is that you can hide your variables inside of a class. The class becomes like a container. Now you as the programmer get to decide how you want the users of your class to interact with it. In Java, the tradition is to provide an API -- a public interface for your class using methods of the class.
To make this approach work, you declare your variables as private ( which means only methods within your class can access them ) and then provide other methods to access them. For example,
private int someNumber;
This variable can only be accessed from within your class. Do you think others might need access to it from outside of the class? You would create a method to allow access:
public int getSomeNumber()
{
return someNumber;
}
Perhaps users of your class will also need the ability to set someNumber as well. In that case, you provide a method to do that as well:
public void setSomeNumber( int someNumber )
{
this.someNumber = someNumber;
}
Why all of this work just to get access to a class member that you could just as easily declare as public? If you do it using this approach, you have control over how others access the data in your class. Imagine that you want to make sure that someNumber only gets set to be a number < 100. You can provide that check in your setSomeNumber method. By declaring your variables to have private access, you protect your class from getting used incorrectly, and make it easier on everyone who needs to use it -- including yourself!
Declaring a variable to have static access means that you do not need an instance of the class to access the variable. In Java, generally you write a class and then create an instance of it. You can have as many instances of that class as you want, and they all keep track of their own data. You can also declare variables that are part of the class itself, and this is where the static keyword comes in. If you create a variable...
static int classVariable = 0;
the variable can be accessed without a class instance. For example, you might see this done from time to time:
public static final int MY_CONSTANT = 1;
While there are better ways to do this now, it is still a common pattern. You use this variable without any instance of the class like this:
myInstance.setSomeNumber( MyClass.MY_CONSTANT );
java.awt.Color uses static variables this way. You can also declare methods to be static ( look at public static void main, the starting point for your programs ). Statics are useful, but use them sparingly because creating instances of classes can often result in better designs.
Finally ( pun intended ), why would you ever want to declare a variable to be final? If you know that the value should never change, declaring it as final means that if you write some code that tries to change that value, the compiler will start complaining. This again helps protect from making silly mistakes that can add up to really annoying bugs.
If you look at the static variable example above, the final keyword is also used. This is a time when you have decided that you want to make a variable public, but also want to protect it from being changed. You do this by making it public and final.