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.
Related
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
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.
In a Java class with static instance fields, is the constructor called every time the fields are accessed, or only on the first access? I initialize the static fields in the constructor, and was wondering if this would cause a slow down because the fields are initialized on every access.
I initialize the static fields in the constructor,
Don't. Never initialize static fields inside a constructor. static fields are not something associated with any instance of a class. It is bound to class. There is only single copy of that variable, that is accessed accross all the instances. So, if you are initializing it in constructor, then every time you create an instance, that field will be re-initialized for every other instance.
You should use static initializer block to initialize your static fields, or just initialize them at the place of declaration.
class Demo {
private static int x; // Either initialize it here.
static { // Or use static initializer block
x = 10;
}
}
with static instance fields, is the constructor called every time the fields are accessed,
No. , static fields are accessed on class. They are loaded and initialized when the class is loaded. And then you can modify it later on, on class name, in which case, the change will be effected for all the instances. So, the constructor will not be invoked, whenever you access static field.
In fact, even when you access instance field, constructor is not invoked every time. Constructor is used to initialize the state of the newly created instance once. And for further access and modification of that field, constructor won't be invoked.
So, a constructor has precisely no role to play whenever you want to access any fields of your class.
The constructor for the object of the static field is called only once, at some point before the field is accessed for the first time. You should not initialize static fields in a regular instance constructor. If they need special initialization, you should supply a static initialization block, like this:
public class Test {
static int[][] a = new int[20][];
static {
for (int i = 0 ; i != 20 ; i++) {
a[i] = new int[i+1];
}
}
}
static variables are loaded when the class is loaded. And only once.
According to the JLS:
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
So this answers your question. i.e.e exactly when the class is loaded :)
Static variables lasts till the JVM is shutdown.
I am wondering when static variables are initialized to their default values.
Is it correct that when a class is loaded, static vars are created (allocated),
then static initializers and initializations in declarations are executed?
At what point are the default values are given? This leads to the problem of forward reference.
Also please if you can explain this in reference to the question asked on Why static fields are not initialized in time? and especially the answer given by Kevin Brock on the same site. I can't understand the 3rd point.
From See Java Static Variable Methods:
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn’t need any object.
Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.
What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.
In case of inner classes, they can not have static fields
An inner class is a nested class that is not explicitly or implicitly
declared static.
...
Inner classes may not declare static initializers (§8.7) or member interfaces...
Inner classes may not declare static members, unless they are constant variables...
See JLS 8.1.3 Inner Classes and Enclosing Instances
final fields in Java can be initialized separately from their declaration place this is however can not be applicable to static final fields. See the example below.
final class Demo
{
private final int x;
private static final int z; //must be initialized here.
static
{
z = 10; //It can be initialized here.
}
public Demo(int x)
{
this.x=x; //This is possible.
//z=15; compiler-error - can not assign a value to a final variable z
}
}
This is because there is just one copy of the static variables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initialize z of type static final within the constructor, it will attempt to reinitialize the static final type field z because the constructor is run on each instantiation of the class that must not occur to static final fields.
Static fields are initialized when the class is loaded by the class loader. Default values are assigned at this time. This is done in the order than they appear in the source code.
See:
JLS 8.7, Static Initializers
JLS 12.2, Loading of Classes and Interfaces
JLS 12.4, Initialization of Classes and Interfaces
The last in particular provides detailed initialization steps that spell out when static variables are initialized, and in what order (with the caveat that final class variables and interface fields that are compile-time constants are initialized first.)
I'm not sure what your specific question about point 3 (assuming you mean the nested one?) is. The detailed sequence states this would be a recursive initialization request so it will continue initialization.
The order of initialization is:
Static initialization blocks
Instance initialization blocks
Constructors
The details of the process are explained in the JVM specification document.
static variable
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution(when the Classloader load the class for the first time) .
These variables will be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn’t need any object
Starting with the code from the other question:
class MyClass {
private static MyClass myClass = new MyClass();
private static final Object obj = new Object();
public MyClass() {
System.out.println(obj); // will print null once
}
}
A reference to this class will start initialization. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null. The constructor is now executed and prints obj, which is null.
Now back to initializing the class: obj is made a reference to a new real object, and we're done.
If this was set off by a statement like: MyClass mc = new MyClass(); space for a new MyClass instance is again allocated (and the reference placed in mc). The constructor is again executed and again prints obj, which now is not null.
The real trick here is that when you use new, as in WhatEverItIs weii = new WhatEverItIs( p1, p2 ); weii is immediately given a reference to a bit of nulled memory. The JVM will then go on to initialize values and run the constructor. But if you somehow reference weii before it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.
The static variable can be intialize in the following three ways as follow choose any one you like
you can intialize it at the time of declaration
or you can do by making static block eg:
static {
// whatever code is needed for initialization goes here
}
There is an alternative to static blocks — you can write a private static method
class name {
public static varType myVar = initializeVar();
private static varType initializeVar() {
// initialization code goes here
}
}
A variable is declared as static to get the latest and single copy of its value; it means the value is going to be changed somewhere. But why should the same variable be declared as final, which will not allow the variable to be changed else where (constant value)?
static so that the variable or method can be accessed without creating a class instance, and there is only one variable for the class instead of one for each instance.
A final class cannot be extended. A final variable cannot have its value changed, it behaves as a constant. And a final method cannot be over-ridden.
The minute a variable is defined as final, it should probably not be referred to as "variable", since it no longer "varies" :)
A static variable is not tied to any particular instance of a class -- it is only tied to the class itself and only from a scoping standpoint.
So there you are -- a static and final variable is actually a value that is not tied to any particular instance of class and does not vary. It is a constant value, to be referenced from anywhere in your Java code.
At some point, when you should decide to change the value of this constant, it only takes one change to propagate this change correctly to all other classes that use this constant.
A variable declared as static means that its value is shared by all instances of this class. Declaring a variable as final gives a slightly better performance and makes your code better readable.
local variables are on the stack and are not static.
You can have a static field which may or may not be final. You would make the field final if it is not going to change.
static fields can be modified (e.g. public static fields can be modified by any class). static final fields cannot be modified after initialization.
Like you mention yourself, this is done to create constants. You create a single field to hold a value with a specific meaning. This way you don't have to declare that value everywhere, but instead you can reference the static.
Static has nothing to do with getting the latest and single copy unless "single copy" here means one and the same value for all the instances of a class (however, I think you may be confusing it with volatile). Static means class variable. You make it final when you want that to be a constant (that's actually the way Java constants are declared: static final).
static final is used in Java to express constants. Static is used to express class variables, so that there is no need to instantiate an object for that class in order to access that variable.
Final methods can't be overriden and final variables can only be initialised once.
If you only use the static keyword, that value will not be a constant as it can be initialised again.
May be to provide something similar to constants.
Variables should be declared as fields only if they’re required for use in more than one method of the class or if the program should save their values between calls to the class’s methods.
for example user.lastName lastName should be field because it is needed during object lifecycle
Variables should be declared as static only if they’re not required for use in more than one method of the class or if the program should not save their values between calls to the class’s methods.
for example Math.max(num1,num2) Im not intristed in num1 and num2 after compleating this operation
Final stops any classes inheriting from it
You create static final variable to make its value accessible without instantiating an object.
E.G.:
public class MyClass
{
public static final String endpoint= "http://localhost:8080/myClass":
/* ...*/
}
Then you can access to the data using this line:
MyClass.endpoint