Class ArrayDemo
Class ArrayDemo
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Here is the output of this program:
a = 42
b = 99
final prevents this from happening: if a field is final, it is part of the JVM
specification that it must effectively ensure that, once the object pointer
is available to other threads, so are the correct values of that object's
final fields.
The fields on any object accessed via a final reference are also
guaranteed to be at least as up to date as when the constructor exits.
This means that:
Thus, immutable objects (ones where all fields are final and are either
primitives or references to immutable objects) can be concurrently
accessed without synchronization. It is also safe to read "effectively
immutable" objects (ones whose fields aren't actually final, but in practice
never change) via a final reference. However, from a program design
perspective, you'd be wise to try and enforce immutability in this case
(e.g. by wrapping a collection in aCollections.unmodifiableList()1 etc). That
way, you'll spot bugs introduced when one of your colleagues naughtily
attempts to modify a collection that you didn't intend to be modified!
When you declare a field final, you must set the value once by the
time the constructor exits. This means that you can declare a final
field as follows:
myList.add("Hello");
One answer to this is "whenever you possibly can". Any field that you
never expect to be changed (be that a primitive value, or a reference to
an object, whether or not that particular object is itself immutable or
not), should generally be declared final. Another way of looking at things
is:
If your object is accessed by multiple threads, and you don't declare its
fields final, then you must providethread-safety by some other
means.
Enum is a keyword which was introduced in Java 5. It is a particular type of class whose
instances are only those objects which are members of that enum. The super class of all enum
objects is java.lang.Enum, apart from this enum can not be extended.
There is another important feature that is every enum requires support from the class library.
When a program compiles and compiler encounters an enum type, it generates a class that
extends the java.lang.Enum, which is a library class.