영어로 읽는 코딩

35_[자바] 초기화 2 (할당)

Specifying initialization

What happens if you want to give a variable an initial value? One direct way to do this is simply to assign the value at the point you define the variable in the class. (Notice you cannot do this in C++, although C++ novices always try.) Here the field definitions in class InitialValues are changed to provide initial values:

//: initialization/InitialValues2.java

// Providing explicit initial values.

public class InitialValues2 {

    boolean bool = true;

    char ch = ‘x’;

    byte b = 47;

    short s = 0xff;

    int i = 999;

    long lng = 1;

    float f = 3.14f;

    double d = 3.14159;

} ///:~

You can also initialize non-primitive objects in this same way. If Depth is a class, you can create a variable and initialize it like so:

//: initialization/Measurement.java
class Depth {}
public class Measurement {
    Depth d = new Depth();
    // ...
} ///:~

If you haven’t given d an initial value and you try to use it anyway, you’ll get a runtime error called an exception (covered in the Error Handling with Exceptions chapter).

You can even call a method to provide an initialization value:

//: initialization/MethodInit.java

public class MethodInit {

    int i = f();

    int f() { return 11; }

} ///:~

This method can have arguments, of course, but those arguments cannot be other class members that haven’t been initialized yet. Thus, you can do this:

//: initialization/MethodInit2.java
public class MethodInit2 {
       int i = f();
       int j = g(i);
       int f() { return 11; }
       int g(int n) { return n * 10; }
} ///:~
 

But yu cannot do this:

//: initialization/MethodInit3.java
public class MethodInit3 {
       //! int j = g(i); // Illegal forward reference
       int i = f();
       int f() { return 11; }
       int g(int n) { return n * 10; }
} ///:~

This is one place in which the compiler, appropriately, does complain about forward referencing, since this has to do with the order of initialization and not the way the program is compiled.

This approach to initialization is simple and straightforward. It has the limitation that every object of type InitialValues will get these same initialization values. Sometimes this is exactly what you need, but at other times you need more flexibility.

 

[Thinking in Java]

댓글

댓글 본문
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기