Static and non static fields - java

just to clarify I am thinking of this right, in java a static field is a variable/field which is used by a whole class, or can be used by all objects refering to that class? And a non static field is a variable defined by an object? And a second object refering to the same class as object 1 can have a different value to object 1's static field?

A static field, or static class variable within a class is accessible before an instance of that class is created unlike instance variables. Instance variables (non-static variables) within a class are created when an instance of that class is created at run-time. Hence, non-static variables cannot be accessed until an instance of that class is created. Whereas, static class members can be accessed before that class is created or instantiated.
All instances of that class can access the same static variable. On the other hand, instance variables are individual/encapsulated to each instance of a class.

static field shared and used by all the objects and loaded when class is loaded
non static fields are separate copies for every object and loaded when an object is created
And a non static field is a variable defined by an object?
Whenever you create a new objects, each object will have its own copy of instance i.e. non static fields
And a second object refering to the same class as object 1 can have a different value to object 1's static field?
Didn't really get your question, but
If object1 and object2 are instnaces of a class, then if object1 modifies static field of class, then object2 will get the updated value

An instance attribute is one that is specific to an instance, and its value isn't shared among other instances of the same class.
On the other hand, a class (or static) attribute is one that is common to all of the class' instances, as it belongs to the class, not to an instance in particular.
So you must be careful with the static attributes, because a change in one will be reflected on all of the code that uses it, sometimes causing unexpected results. In practice, I tend to avoid static attributes, except for the cases where they have constant, immutable values.
Similar considerations apply to instance methods and static methods: an instance method can "see" both instance and static methods and attributes, whereas a static method can only refer to static methods and attributes of the class, and can't "see" the instance methods and attributes (that is unless it instantiates an object and uses it to access its instance members).

Kind of... a static object is shared between instances of a class and a non-static is specific to the instance. Same goes for methods.

As said in the reference :
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 (§12.4).

Refer to JLS §8.3.1.1:
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 (§12.4).
By contrast, each instance of a class contains its own unique values for non-static fields. Non-static fields are incarnated when the class is instantiated:
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 (§12.5), a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.

Related

What members of the enclosing class can a static nested class access?

Java The Complete Reference says
A static nested class is one that has the static modifier applied. Because it is static, it must access the non-static
members of its enclosing class through an object. That is, it
cannot refer to non-static members of its enclosing class
directly. Because of this restriction, static nested classes are
seldom used.
What does it mean by "through an object", and "cannot ... directly"?
Java in a Nutshell says
• A static member type can access (only) the static members of the class that contains it.
• A static member type has access to all the static members (including any other static member types) of its
containing type.
Are the two sentences redundant to each other? What are the differences between the two sentences?
Do the quotes from the two books contradict each other? The first
quote says a static nested class can access non-static member of the
enclosing class, while the second quote says a static member type
can access only the static members of the enclosing class.
Thanks.
In Java nested non - static classes have a hidden reference to the instance of the parent class. That's why they can access all non-static members. The nested class doesn't have such an instance. However, its scope allows it to access the parent members if the parent class passes this.
So what the second quote is saying that the access doesn't happen automatically. You pass the reference to the enclosing class and the nested static class can access it. Otherwise, it doesn't know the address of the enclosing class.
No static method may access an instance field directly without first qualifying it with an object of the containing class.
class Foo {
int myField;
public void main(String[] args) {
Foo foo = new Foo();
access(foo);
}
public static void access(Foo obj) {
System.out.println(myField); // <-- error, can't access myField from static
//context.
System.out.println(obj.myField); // OK here
}
}
The same is true for accessing instance fields via inner static classes.
A java static nested class can access the static members of the nested class and the static members of the parent class. This makes sense when you understand the position of a class and object in memory – that there is only one class but multiple objects and you need to decide what each instance of an object needs absolutely necessarily and what is actually redundant and can stay in the class (doesn't need to be duplicated), so all methods (static and non static) and all static members
What members of the enclosing class can a static nested class access?
You can gain clarity to the answer for this question by assigning the following meaning for the Java keyword static:
"Static" in Java means without regard for or association with any instance of any class.
A static field belongs to the class in which it is declared and is not encapsulated by any instance of that class. Any instance of the class that is subsequently constructed (or any instance or any method of any class that is in scope) can access the static field (this is why static fields can be dangerous in concurrent environments).
A static method is defined for the class in which it is declared and has no associated instance of that class. A static method knows of no class instances and can not access any of them unless a reference to an instance is passed to it as an argument.
A static member class is in every way that matters the same as an ordinary top level class that has been packaged within an enclosing class for packaging convenience. Just like a top level class, its instances know nothing of any instance of the enclosing class (unless a reference to an enclosing class instance is passed to them during construction).
A static initializer block is used to initialize static fields for a class, but it knows nothing of any instances of that class. Therefore, they cannot initialize instance fields since they cannot access them.
Therefore, the answer becomes intuitive: a static nested class can access all members of an enclosing class that can be accessed without an instance of that class.
If an enclosing class instance is passed to the static nested class's constructor, then the members of that instance (including the private ones) will be in scope. Logically, passing an enclosing class instance to a static nested class constructor is very similar to using a nested member class. The difference is that for the former, the association is an explicit dependency injection; whereas for the latter, the association between instances is implicit.

How does the static keyword work in Java?

I'm reading Java tutorials from the begining and I have a question about static keyword on fields or variables. As Java said here:
Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances.
With that, I guess that if you have an object (in this case, an instance of the class Bicycle) and a field inside of it that its static then, independently of if you are refearing to bicycle1 or bicycle2, the field that its static will have the same value. Am I wrong or I understand it well?
I mean, if I have:
Bicycle bicycle1 = new Bicycle();
Bicycle bicycle2 = new Bicycle();
and in the class Bicycle I have a static field like:
class Bicycle{
static int gears;
//Methods to set and get gears
}
And in the bicycle1 I set the value of gears to seven:
bicycle1.setGears(7);
then if I try to get the value of gears in bicycle2 I should get the same value as I set on bicycle1, right?
System.out.println(bicycle2.getGears()); //7
Well, here is where I have the doubt because as Java said in the quote that I put above:
this tells the compiler that there is exactly one copy of this variable in existence
Where is this copy stored? How the objects access to that copy? When is this copy created?
Where is this copy stored?
The copy (static variable) is stored in the Permanent Generation section, but if you use Java8 the Permanent Generation section no longer exists.
The static variables and static methods are part of the reflection data which are class-related data and not instance-related.
How do the objects access that copy?
Every instance of class (object) that you have created has a reference to the class.
When is this copy created?
It is created at runtime when the class is loaded: this is done by the classloader of the JVM when the class is first referenced.
Static variables belong to the class, and not to instances of the class.
Your intuition is right - you have only one copy regardless of how many object you create.
You can access a static variable using the name of the class, like in this example:
class Static {
static int staticField;
}
public class UseStatic {
public static void main(String[] args) {
System.out.println(Static.staticField);
}
}
The static fields are useful to create some kind of class constants.
Finally, to easily initialize a static field of a specific class you can use Static Initialization Blocks.
Sources: University course on java, java official documentation
With that, I guess that if you have an object (in this case, an
instance of the class Bicycle) and a field inside of it that its
static then, independently of if you are refearing to bicycle1 or
bicycle2, the field that its static will have the same value. Am I
wrong or I understand it well?
When you instantiate a class in Java for the first time, the JVM creates two things:
an instance. A set of non-static fields is allocated onto the heap for each of the instances that you create. These instance fields are separate from all other instances (and are used to represent their object's state).
a Class object. Every class in Java has one, and only one, Class object ... no matter how many instances of it that are created. For example, the Class object for class String is Class<String> (which is expressed as a literal as String.class). You can think of the static fields of a class as belonging to the Class object. The lifecycle of Class objects is independent of the lifecycle of class instances; Class objects exist for as long as the JVM process is running (therefore, their static fields also exist that long).
Since a class has only one Class object, and since all instances of a class share that same Class object, the static fields of a class are shared by all the class instances that exist.
In general, it is useful to think of the static keyword as meaning "independent of any instance":
a static field belongs to the Class object and not to any instance
a static method is invoked through the Class object and has no direct access to any instance
a static member class instance is not dependent on any other instance
static variables in java are stored in the class, you don't need to create a instance of it to access them.
class Bicycle{
public static int gears = 7;
//Methods to set and get gears
}
You can access the static method like this
Bicycle.gears;
So, there's just one Bicycle class declared on java, when you instantiate a class it's create one instance of bicycle with all static attributes declared.
Where is this copy stored?
Static variables are stored in some static storage (in permgen, I believe), you should not bother about it.
When is this copy created?
They are created when class is accessed first time (loaded by class loader) and never deleted (unless class is unloaded)
How the objects access to that copy?
Instance has reference to its class, and class has reverence to all its variables. How exactly C structures are laid in memory is implementation-specific detail.
Since static vars are bound to class, not instance, you do not even need to instantiate class to access them. MyClass.myStaticVar is ok.

naming practice of variables in java. why class variable not package variable

i am just curious why class variable (i.e variables with static keyword) its called class variable instead of package variable. I mean if I declare a static variable in one class, i can access this variable from another class in the same package as long as it is not private.
Also, instance variables are declared inside a class and methods in that class can access instance variables, why not name them class variables... I just don't get it.
The class is basically the frame or blueprint for creating instances (objects). Static variables and methods are defined inside the frame and created when the class is loaded by the ClassLoader, so no instance needs to be created for them to exist. That's why they are class variables. They are not package variables because they belong specifically to that class. I.e. you would access them by calling MyClass.myVariable.
Instance variables only come into existence when an instance of the class i.e. an object is created by calling new(), and they are specific to that object and not specific to the class. There are as many counts of an instance variable as the number of objects of that class are created, whereas there is always just one count of the static class variable. That is why they are called instance variables, because they are specific to an instance and not to the class.
It's called class variable because it is inside a Class. Visibility doesn't matter in the naming convention.
And a non-static variable is a instance variable because it can be different among instances of a class. A Method is always the same among all the instances of that class.
Because packages consist of groups of classes working together, whereas classes are the abstractions that make up the objects in the implementation. You cannot have variables exist purely as package variables because it wouldn't give a context for which class "owns" the variable. Plus, it's just bad Object Oriented Programming.

Java clarification on instance and static variable usage from within instance and static methods?

Question in my book is asking: What restrictions are placed on instance variable and static variable access from within the definition of: 1.) An instance method? 2.) A static method?
Is my response to this concept correct?
-An instance method cannot directly access the instance variable while a static variable can be directly accessed since one copy is used throughout the class. (Each object will share this static variable as well as the static methods in the class. An instance variable is only available to each object and each object has its own copy of this instance variable.) A static method cannot access instance members of the class. A static method can however access members of the static variable.
An instance method cannot directly access the instance variable
Wrong.
while a static variable can be directly accessed since one copy is used throughout the class.
Correct.
(Each object will share this static variable as well as the static methods in the class.
Correct.
An instance variable is only available to each object and each object has its own copy of this instance variable.)
Correct.
A static method cannot access instance members of the class.
Correct.
A static method can however access members of the static variable.
Correct, if it has members, and they are accessible.
The compiler would have told you all this with 100% reliablity.
That's right, simply put:
Instance methods can access instance and static variables of the same class (if other access modifiers permit so);
Static methods can only access static variables of the same class.

Constraint on static

static methods can call only static methods/fields from same class. Questions:
Why non static methods/fields shall not be made available to static because once static method has been called then JVM has created an object for it, which can access other parts of class if JVM allows?
Why does static methods allow objects from non static methods of other classes. Imposing restriction that they can access only static of other classes and letting a static access non static members of same class will cause any difference?
Following is the java language specification for the static methods and fields. Hope it will help you
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 (§12.4).
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 (§12.5), a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
8.4.3.2. static Methods
A method that is declared static is called a class method.
It is a compile-time error to use the name of a type parameter of any surrounding declaration in the header or body of a class method.
A class method is always invoked without reference to a particular object. It is a compile-time error to attempt to reference the current object using the keyword this (§15.8.3) or the keyword super (§15.11.2).
A method that is not declared static is called an instance method, and sometimes called a non-static method.
An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.
A non-static method has an implicit this object to can call on other non-static methods
A static method cannot implicitly call a non-static method as it has no object to implicitly use. There is nothing to stop you explicitly using an object to call a method.
e.g.
class Main {
public static void main(String... ignored) {
new Main().nonstatic(); // calls non-static method
}
public void nonstatic() {
nonstatic2(); // calls non-static object with implicit reference to "this"
}
public void nonstatic2() {
staticMethod(this);
}
public static void staticMethod(Main main) {
main.nonstatic3(); // static calls non-static with explicit object.
}
public void nonstatic3() {
}
static methods can call only static methods/fields from same class.
This is not true as the example shows.
Why non static methods/fields shall not be made available to static because once static method has been called then JVM has created an object for it,
The JVM could create an object automagically, but this is unlikely to be useful, esp if the object has no default constructor.
which can access other parts of class if JVM allows?
It could allow, but shouldn't IMHO as this would be more confusing than useful.
Why does static methods allow objects from non static methods of other classes.
static methods allow objects from all classes, not just other ones.
Imposing restriction that they can access only static of other classes and letting a static access non static members of same class will cause any difference?
The difference is you don't have an implicit instance of the class This is the whole point of a static method.
If you wanted an implicit instance, you would use a non-static method.
once Static method has been called than JVM has created an object for
it
This is not true. Static methods can be called without creating an object of that class defining static method (remember public static void main()).
Why does Static methods() allow objects from nonstatic methods of
other classes.
This is because other classe instance can exist irrespective of whether object of class defining static method (which access the the other class) exists.
Checkout this link for further insights.
In order to understand why static methods cannot call non static methods or access non static variables you need to understand the diffeerence between a class and an object.
Java is an object oriented language. First you define a class which holds the state(instance variables) and methods which change the state(instance variables).
But class is not an object. It is just a template for object creation, for which you use the new keyword (creating an instance of class).
Once you create an object its variables are in an inital state, and then you call methods which read or change object's state. Such variables and methods are non static in the sense that they require an object instance of a class.
However, in a class you can define a method that does not read or change the state. Method's behavior is not dependent at all on instance variables.
Such method can be declared static, which means no instance of the class is required to run the method.
You call a static method directly on a class ( without a reference to an object ):
MyClass.staticMethod();//will not read or change any state, because there is no object here
You can also call a static method on an object but will not access object's state, because its behavior does not depend nor does not change object's state. Call to obj.staticMethod(); is the same as MyClass.staticMethod();:
//Create an instance of a MyClass
MyClass obj = new MyClass();
//will not read or change any state of obj.
obj.staticMethod();
Note however that static methods are not completely stateless, they can still read or change the state of static varibables.
Note also that in Java you cannot override static methods(unlike in Delphi) - don't declare a method as static if you think subclasses will need to override it.
Therefore as rule-of-thumb declare static methods in special purpose utility classes which don't need an instance anyway, like for example java.lang.Math, otherwise
don't declare a method as static even if it doesn't read or change object's state because you might need to override it later.
Why non static methods/fields shall not be made available to static because once static method has been called then JVM has created an object for it, which can access other parts of class if JVM allows?
If static methods were allowed to access non-static methods, that would mean, an instance level method would be called without an instance of the class. Then how will you override the method?. Overriding looks at the object to call/invoke the method and if you directly call non-static (instance) methods from static methods, which object is being used to call?.
And from a design perspective -
Assume you have a class called Dog.
Every dog eats, sleeps etc . But the most important thing to remember is all these things are specific to the Dog instance. and state of each object should be accessed via instance level methods - thats the whole point of encapsulation. If you say Dog.sleep(). Which dog should sleep?

Categories