Can you
access non-static variable in static context?
Static-variable in Java belongs to Class and
its value remains the same for all instances. static variable initialized
when class is loaded into JVM on the other hand instance variable has different
value for each instance and they get created when the instance of an object
is created either by using a new() operator or using reflection
like Class.newInstance(). So if you try to access a non-static
variable without any instance compiler will complain because of those
variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance.
Example of accessing a non-static variable inside a static context:
Example of accessing a non-static variable inside a static context:
public class
StaticTest {
|
private int count= 0;
|
public static void
main(String args[]) {
|
StaticTest test =
new StaticTest();
|
System.out.println(test.count++);
|
}
|
}
|
Types of memory
areas are allocated by JVM :
·
Class(Method)
Area
·
Heap
·
Stack
·
Program
Counter Register
·
Native
Method Stack
No comments:
Post a Comment