Initializer blocks are similar to variable initializers used to initialize variables. The difference is that with an initializer block, you can code more than one statement. Here’s a class that gets the value for a class field from the user when the class is initialized:
class PrimeClass { private Scanner sc = new Scanner(System.in); public int x; { System.out.print( "Enter the starting value for x: "); x = sc.nextInt(); } }
You can almost always achieve the same
effect by using other coding techniques, which usually are more direct.
You could prompt the user for the value in the constructor, for example,
or you could call a method in the field initializer, like this:
class PrimeClass { private Scanner sc = new Scanner(System.in); public int x = getX(); private int getX() { System.out.print("Enter the starting value " + "for x: "); return sc.nextInt(); } }Either way, the effect is the same.
Here are a few other tidbits of information concerning initializers:
-
If a class contains more than one initializer, the initializers are executed in the order in which they appear in the program.
-
Initializers are executed before any class constructors.
-
A special kind of initializer block called a static initializer lets you initialize static fields.
-
Initializers are sometimes used with anonymous classes.
How to Use Initializers in Java
@reference_3_javaworld.com
Java 101: Class and object initialization in Java
Class Initializers
The fifth line (or block of lines) is a class initializer block. It begins with a{
and ends with
a }
. Inside this block you can put initialization code that is to be executed a instance of the class
is created. In this example the block is empty. The text inside the block is just a comment.
The Java compiler ignores it.
{ //class initializer }Class initializers can also be static. Then they are executed already when the class is loaded, and only once because the class is only loaded in the Java Virtual Machine once. Here is an example of a static initializer block:
static { //static class initializer }Notice the keyword
static
before the block. This makes the class initializer block static.
@reference_4_jenkov.com
Java Syntax
No comments:
Post a Comment