I have noticed that there are times when coding in Java that I have seen fields called by method:
System.out.println(object.field);
and
Refrencing a field by class requires the field to be static.
Refrencing a field by object requires the field can be either static or non-static field .
The field Class.field
can be accessed without creating an instance of the class. These are static
fields which are initialized when the classes are loaded by classloaders.
The other field i.e. object.field
can be accessed only when an instance of the class is created. These are instance
field initialized when object of the class is created by calling its constructor.
My intuition is that the class calling will be used for static fields
Yes SomeClass.field
can be used only if field
is static
. In this case you can also access it via reference like someClassRef.field
but this code will be changed by compiler to ReferenceType.field
anyway. Also it can cause some misunderstandings (it may seem that you are trying to use non-static field) so it is better to use static fields by its class.
If field
is not static then it must belong to some instance so you will have to call it via reference someClassRef.field
Instance scope versus class scope.
Check this out:
class Foobar {
public final int x = 5;
public static final int y = 6;
}
y
is a variable that is only created once, at compile time. It is bound to the class, and therefore shared by all of its instances. You reference this with Foobar.y
.
System.err.println(Foobar.y);
x
on the other hand, is an instance variable, and every Foobar
that you create with new
will have a copy of it. You would reference it like this:
Foobar foobar = new Foobar();
System.err.println(foobar.x);
But this will not work:
System.err.println(Foobar.x);
object.field
should be (see note below) an instance member while Class.field
would be a static member.
Note: Like stated by @radai and I think it's worth mentionning, you can also access a static member through an object instance, however that's a very bad practice which is quite misleading.