I am studying about static variables. They say that static variables are class variables.
They gave an example like this
class Bicycle{
private static int noOfBicycles = 0;
}
When calling this we can directly use the name of the class to call this variable without creating any object, i.e.
Bicycle.noOfBicycles
So when do we need these static variables rather than instance variables?
When a variable is declared as static, a single copy of the variable is created and shared among all objects at a class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
Instance variables are non-static variables and are declared in a class outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
The main differences between static and non static variables are
better explained here
Also already answered Static vs Instance Variables: Difference?
Related
JMenuItem print = new JMenuItem("Print");
print.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
I'm new to java. I have learned that if we want to access the contents of class then we have to first create an object of that class. Then we can use that object to access the class's contents.
But here KeyEvent and ActionEvent are classes and they can access their fields VK_P and CTRL_MASK without the help of any object. How is this possible?
Static variables, or variables initialized with a static keyword, are able to be accessed without instantiation of a class object since they are not tied to a particular instance of the class but the actual class itself.
You can access a class's variable without via an instance of that class if that variable is static.
Static variables, or variables declared with a static keyword, are class level data members
NOT instance/object level.
This means - the same static variable is common to all instances of the class and they all can access it (!!).
public class Perrson{
public static int personCounter;
mean:
you can access personCounter as Person.personCounter++ for instance..
However, when you have Person instances p1, p2,...
p1.personCounter++
p2.personCounter++
access the same variable !
It is good for example for object counter when Person constructor advances the counter.
by yl
Will a static variable from the parent class be inherited as is to the child class, or will a new variable be created?
For example, should a static counter variable of class A and class B extends A give the same value (if we have not defined a new counter for class B) ?
No, Static variable does not behave like non-static variables. If you change value of static variable with one of the inherited class it will effect all other inherited class data.
Cause static variable is created only once. Even though you are creating multiple objects the static variables are not created again and again. They are created at starting time of execution and stored. When ever you access static variable you will get same variable.
i.e
if you are accessing as B.count or C.count you will get same variable.
So you are having only one variable then you can't maintain count separately for two objects in single variable.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have been searching for clear answers desperately and I think I kinda get it but at the same time I don't quite get the broad concept of that keyword, static.
Here's the scenario I've made:
package oops;
public class Math {
boolean notNumber = false;
static boolean notString = false;
public static void main(String[] args) {
int num1 = 1;
static int num2 = 1; //doesn't work
Math math = new Math();
math.notNumber = true;
notNumber = true; //doesn't work
notString = true;
}
public void whatever() {
notNumber = true;
}
}
Why can't you declare a variable as static inside the static method (or any method)? What does "scope" mean? I know that static variables are not associated with a particular instance of a class, it's more like a "global" variable. But why can't you create a static variable inside the method (num2), but can USE the static variable (notString)?
When you make static variables, do you HAVE TO make them in the class? Not possible in the methods?
Since I declared notNumber as non-static, I know I have to create an object to access that variable. But why does it work in whatever() without any creation of objects, but not in the static method main()?
But why can't you create a static variable inside the method (num2),
but can USE the static variable (notString)?
When you make static variables, do you HAVE TO make them in the class?
Not possible in the methods?
static is scoped to the class context. So declaring a static variable in a method scope makes no sense.
It is like if you declared an instance field in a method.
Declaring a variable and using it are two distinct things that don't obey to the same rules.
As a rule of thumb, you declare a variable with a specific modifier in a place that fits to this modifier. For example :
instance and static fields at the class top level
local variables at the method level
And you use a variable with a specific modifier in any context that is compatible with this modifier :
instance variables in an instance context
static variables both in instance and static contexts.
Since I declared notNumber as non-static, I know I have to create an
object to access that variable. But why does it work in whatever()
without any creation of objects, but not in the static method main()?
This is an instance method :
public void whatever() {
notNumber = true;
}
So it is valid to access to instance members of the class.
While this other is a static method. So it can refer static fields but not instance fields :
public class Math {
boolean notNumber = false; // instance
static boolean notString = false; // static
public static void main(String[] args) {
...
notNumber = true; //doesn't work as refers an instance field
notString = true; // work as refers a static field
}
...
}
Because there is absolutly no need to declare static viriables in methods.static variables are members shared by all instances of this class. Suppose it is allowed to declare it in main method, and you have another static method foo, then how can you access this variable in foo?
You seem to understand that static members don't belong to any instance. They belong to the class itself. They are not really "global" like you have said. You still need to write the class name first when you want to access them from another class. Because static members belongs to the class, the only sensible place for them to exist is at the class-level. You can't declare them in methods because it would make them seem like they belong to methods (as in, their scope is the method body), which they don't. You can use them in methods of the same class without qualifying the class name though, because the method is in scope of the class.
They have to be in the class, as mentioned above.
This is a good question. If you look carefully, whatever is not static either! That means you have to have an instance first, before whatever can be executed. This instance, in whatever, is referred to as "this". Your use of notNumber is short for this.notNumber. You are using the notNumber field of the instance on which whatever is called.
Let us answer it one by one. But before that let us understand what is static variable and what is non-static variable. The static variable is a variable that belongs to a Class and not to any specific instance of the class whereas on the other hand a non static variable belongs to a class instance.
So consider below example
class A{
static Object someStaticValue;
Object someNonStaticValue;
}
A.someStaticValue = new Object(); //allowed
A.someNonStaticValue = new Object() //not allowed as someNonStaticValue belongs to instance of A and will be different for each instance of A
A objectA = new A();
objectA.someNonStaticValue = new Object(); //allowed as this will update someNonStaticValue which is in scope of objectA
objectA.someStaticValue = new Object(); //allowed as it will simply update the value of variable in Class scope.
A objectB = new A();
objectB.someNonStaticValue = new Object(); //allowed
objectB.someStaticValue = new Object(); //allowed as it will simply update the value of variable in Class scope.
objectA.someNonStaticValue is not equal to objectB.someNonStaticValue
as they belong to two different scope
whereas A.someStaticValue, objectA.someStaticValue,
objectB.someStaticValue -> All are equal as they are updating the
variable in class scope.
Now coming to your questions:
Why can't you declare a static variable in a static or non-static method?
Any variable declared inside a method will have scope inside a method and hence can never belong to a class. Every time you will call that method a new instance will be used and hence will be different for each call and hence no purpose of making a variable static inside a method
When you make static variables, do you HAVE TO make them in the class?
Not possible in the methods?
Yes, because creating in methods will solve no purpose and will not be able to keep the definition of static as the values will change in different calls to that method.
Since I declared notNumber as non-static, I know I have to create an
object to access that variable. But why does it work in whatever()
without any creation of objects, but not in the static method main()?
Because in whatever() function, it is sure that you have created a new instance of the class using which you have called this function, calling a non-static variable inside a non-static variable is allowed. Also, in this case, its clear to JVM which instance scope to use for this variable. However, when it comes to static method, there is no guarantee that the instance of the class has been created or not and also of which class instance scope to be used for that non-static variable. Hence, calling non-static variable from a static method is not allowed.
Why can't you declare a variable as static inside the static method (or any method)? What does "scope" mean? I know that static variables are not associated with a particular instance of a class, it's more like a "global" variable. But why can't you create a static variable inside the method (num2), but can USE the static variable (notString)?
ANSWER: You can not declare varibale as static inside a method.
Inside method all variables are local variables that has no existance outside this method thats why they cann't be static.
But why does it work in whatever()?
ANSWER: because
boolean notNumber is declared on class level, and whatsoever method is non static that's why. you cannot reference non static in static
WHY YOU CANNOT REFERENCE NON STATIC IN STATIC?
Why non-static variable cannot be reference from a static context - reg
When you make static variables, do you HAVE TO make them in the class? Not possible in the methods?
ANSWER you cannot make static variables inside static method. SEE FIRST ANSWER
There is not much to explain. The title is enough to explain the question. I got this on an interview today.
What are class variables and member variables in Java?
Thank you!
As Zhuinden said they probably meant static variables instead of class variables. For member variables, an instance of the class is needed in order to access the variable. For example if I had a class Foo, and it had a member variable int bar, the only way I could access it is by doing something like
Foo foo = new Foo();
doSomething(foo.bar);
However, if I have bar was a static variable, that means that I can access it even though I don't have an instance of the object. I would access it like this:
doSomething(Foo.bar)
without having to create an instance of Foo.
See here
A member variable is one per object, every object has its own copy of instance variable while a class variable is one per Class, every object of that class shares the same class variable..
A class variable also called as static variable is initialized when the JVM loads the class probably take an example static block if there is no main method in your program while this is not the case with your member variables.
Class variables should be used when you don't want to have copy for each instance while
member variables should be used when you want separate copy for each instance of object.
From point of garbage collection class variables have a long life as class variables are associated with the class and not individual instance.
class variables are cleaned up when the ClassLoader which hold the class unloaded. This is very rare..while in case of member variables they get cleaned up when the instance is cleaned up. Hope this helps.
I have a simple question here.
If I declare a variable inside an object which was made [declared] in the main class, like this:
public static int number;
(
usually I declare it like this :
private int number;
)
can it be used in a different object which was also made [declared] in the main class?
btw I do not care about security atm, I just want to make something work, don't care about protection)
Here's a telling quote from Java Language Specification:
JLS 8.3.1.1 static Fields
If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized.
A field that is not declared static (sometimes called a non-static field) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
[Example program follows...]
In short, a static field is a class variable: it belongs to the class, as opposed to the instances of the class. In a way, you can think of a static field as a variable shared by instances of the class, but it's much more consistent to think of static fields as belonging to the class, just like static method also belongs to the class, etc.
Since they belong to the class, they do not require an instance of said class to access (assuming adequate visibility), and in fact it's considered bad programming practice to access static members through an instance instead of a type expression.
Related questions
Java - static methods best practices
Static methods
calling non-static method in static method in Java
non-static variable cannot be referenced from a static context (java)
When NOT to use the static keyword in Java?
Static variables and methods
If the class holding 'number' is called MyClass
you can refer to it as MyClass.number from any method.
Doing so for a variable is not good design though.
There are really two issues here: public vs. private in the context of inner classes, and static variables.
Part 1:
static means that you don't need an instance of the class to access that variable. Suppose you have some code like:
class MyClass {
public static String message = "Hello, World!";
}
You can access the property this way:
System.out.println(MyClass.message);
If you remove the static keyword, you would instead do:
System.out.println(new MyClass().message);
You are accessing the property in the context of an instance, which is a copy of the class created by the new keyword.
Part 2:
If you define two classes in the same java file, one of them must be an inner class. An inner class can have a static keyword, just like a property. If static, it can be used separately. If not-static, it can only be used in the context of a class instance.
Ex:
class MyClass {
public static class InnerClass {
}
}
Then you can do:
new MyClass.InnerClass();
Without the 'static', you would need:
new MyClass().new InnerClass(); //I think
If an inner class is static, it can only access static properties from the outer class. If the inner class is non-static, it can access any property. An inner class doesn't respect the rules of public, protected, or private. So the following is legal:
class MyClass {
private String message;
private class InnerClass {
public InnerClass() {
System.out.println(message);
}
}
}
If the inner class has keyword static, this would not work, since message is not static.
static variables are shared by all instances of a given class. If it's public, it is visible to everything.
non-static variables belong to only one instance.
Since your main method is static, it can only see static variables. But you should avoid working statically - make an instance of a class, and pass the data around as method/constructor parameters, rather than sharing it via static variables.