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
Related
Why can we access a static variable via an object reference in Java, like the code below?
public class Static {
private static String x = "Static variable";
public String getX() {
return this.x; // Case #1
}
public static void main(String[] args) {
Static member = new Static();
System.out.println(member.x); // Case #2
}
}
Generally, public variables can be accessed by everybody, and private variables can only be accessed from within the current instance of the class. In your example you're allowed to access the x variable from the main method, because that method is within the Static class.
If you're wondering why you're allowed to access it from another instance of Static class than the one you're currently in (which generally isn't allowed for private variables), it's simply because static variables don't exist on a per-instance basis, but on a per class basis. This means that the same static variable of A can be accessed from all instances of A.
If this wasn't the case, nobody would be able to access the private static variable at all, since it doesn't belong to one instance, but them all.
The reason that it is allowed is that the JLS says it is. The specific sections that allows this are JLS 6.5.6.2 (for the member.x cases) and JLS 15.11.1 (in both cases). The latter says:
If the field is static:
If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
If the field is not final, or is a blank final and the field access occurs in a class variable initializer (§8.3.2) or static initializer (§8.7), then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
Why are these allowed by the JLS?
Frankly, I don't know. I can't think of any good reasons to allow them.
Either way, using a reference or this to access a static variable is a bad idea because most programmers are likely to be mislead into thinking that you are using an instance field. That is a strong reason to not use this feature of Java.
In your first and second cases you should reference the variable as x or Static.x rather than member.x. (I prefer Static.x.)
It is not best practice to reference a static variable in that way.
However your question was why is it allowed? I would guess the answer is to that a developer can change an instance member (field or variable) to a static member without having to change all the references to that member.
This is especially true in multi-developer environments. Otherwise your code may fail to compile just because your partner changed some instance variables to static variables.
static variables are otherwise called as class variables, because they are available to each object of that class.
As member is an object of the class Static, so you can access all static as wll as non static variables of Static class through member object.
The non-static member is instance member. The static member(class wide) could not access instance members because, there are no way to determine which instance owns any specific non-static members.
The instance object could always refers to static members as it belongs to class which global(shared) to its instances.
This logically makes sense although it is not interesting practice. Static variable is usually for enforcing single declaration of variable during instantiation. Object is a new copy of Class with other name. Even though object is new copy of class it is still with characteristics of the (uninstantiated) Class (first invisible instance). Therefore new object also has that static members pointing to the original copy. Thing to note is: New instance of StackOverflow is also StackOverflow.
I didn't understand this part:
Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName.
Can you give an example please ?
Static methods are methods that are called without a reference to an instance of that object. So instance variables cannot be called statically, as each instance will have its own values. So in a static method, you need a specific instance of an object in order to know which value of the instance variable you are trying to use.
The difference is how you access these variables:
class myClass {
public static int staticVar;
public int nonStaticVar;
//Constructor initialises both
}
Static approach:
int otherVariable = MyClass.staticVar;
As you can see, for the static variable you do not need to make an object to access it. Note that you can imagine a static variable to have the trait "once per class", which means, that you can not have 2 versions of staticVar.
Non Static (instance variable):
MyClass instanceOfMyClass = new myClass();
int otherVariable2 = instanceOfMyClass.nonStaticVar;
To have 2 versions of nonStaticVar you can simply make 2 objects and give this variable different values in the 2 objects. Note that in this case you have to make an object.
I have my main class from which i call my sub class.
My sub class contains some public static variables like
public class SubClass2 extends Main {
public static long a = 0;
public static long b = 0;
public static long c= 0;
public void Analyze(int number)
{
b=2;
//some code
}
}
Where as in main i call the object of the SubClass2.I want everytime when i make the new object of the subclass2 in main then it initializes
all the variables =0 but when i take the print statement of the variable b.It prints out like 4.It adds up the previous value with the new value.
Your fields should not be declared as static in that case. This is why they're not being initialised each time. A static field is initialised once only, then shared by every instance of the class, and depending on accessibility, also outside of the class.
The logic that led to the value 4 must be in the code you've replaced with //some code, but this ins't really relevant here.
If for whatever reason these really should be static fields that are initialised each time an instance is instantiated, then you would have to initialise them manually in the class's constructor. But I'd seriously question the design that leads to this situation...
You are using static variables. These have no connection to any objects you create. They are just global, unique variables. You must erase static. By the way, it is redundant to initialize a field to 0. It is already initialized to zero.
If you use the word static there will only ever be one instance of the variable that is shared between everything created that uses it. Remove static and there will be a new, but more importantly, individual variable for each time its initialised in a method.
Perhaps better wording is that instance methods can and will access shared/static variables!
Your question embodies a contradiction in terms. Static variables are initialized once, when the class is loaded. If you want variables initialized per-instance, use per-instance (non-static) variables.
I want to know if it is possible to use a static variable inside a non static methode ?
also
can I use a non static variable inside a static methode ?
Thanks
A static variable can be accessed from anywhere you like.
A non static variable can only be accessed from a non static method or from a specific object (instance of a class).
The reason for this can get quite complicated, but in brief:
Anything that is non static in your class is duplicated whenever an object is instantiated from that class. Anything static is common to all instances of the class (and not duplicated for new objects), meaning it is unaffected by changes in the state of individual objects.
Now obviously until an instance of the class has been created, anything non static cant exist - there's no object for them to belong to. Since static members dont require an instance of a class to exist, it wouldnt be safe for them to access members that do require an instance of an object (non static).
Both are possible, but to access an instance (non-static) variable you need an instance.
This can be given implicitly in a non-static context like in an instance method, and must be provided explicitly in a static context.
class StaticOrNot {
static int staticVar = 1;
int instVar = 2;
static void staticMethod() {
staticVar += 1;
StaticOrNot someInstance = new StaticOrNot();
someInstance.instVar += 2;
}
void nonStatic() {
staticVar += 1;
instVar += 2; // using this as instance
}
}
I want to know if it is possible to use a static variable inside a non static methode ?
Yes.
can I use a non static variable inside a static methode ?
No.
Think about what it means to use a non-static variable in a static context. A static method is not executing on any instance - therefore, what would it mean to operate on a member field defined on the class? What instance does that field belong to? None!
The opposite scenario, namely, using a static variable in a non-static context makes perfect sense. You're on an instance, and you want to read some static reference that is defined for all instances of a given class.
I want to know if it is possible to use a static variable inside a non static methode ?
Yes.
can I use a non static variable inside a static methode ?
Only if you have an instance of the class available inside that static method.
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.