View on GitHub

我的学习笔记

好记性不如烂笔头

5.6 成员初始化

package initialization;
//: initialization/initialValues.java
// Show default initial values

public class InitialValues{
    boolean t;
    char c;
    byte b;
    short s;
    int i;
    long l;
    float f;
    double d;
    InitialValues reference;

    void printInitialValues(){
        System.out.println("Data-type   InitiaValue");
        System.out.println("boolean     "+t);
        System.out.println("char        "+c);
        System.out.println("byte        "+b);
        System.out.println("short       "+s);
        System.out.println("int         "+i);
        System.out.println("long        "+l);
        System.out.println("float       "+f);
        System.out.println("double      "+d);
        System.out.println("reference   "+reference);
    }

    public static void main(String[] args) {
        InitialValues iv=new InitialValues();

        iv.printInitialValues();

        //  new InitialValues().printInitialValues();
    }
}/*OutPut:
Data-type   InitiaValue
boolean     false
char
byte        0
short       0
int         0
long        0
float       0.0
double      0.0
reference   null
*///:~

out

5.6.1 指定初始化

//: initialization/InitialValudes2.java
// Provide 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;
}///:~
//: initialization/Measurement.java
class Depth{}
public class Measurement{
    Depth d=new Depth();
    //...
}///:~
//:initalization/MethodInit.java
public class MethodInit{
    int i=f();
    int f(){return 11;}
}///:~

这个方法也可以带有参数,但这些参数必须是已经被初始化了的

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