1.基本数据类型初始化
类成员的初始化,各基本数据类型的默认值,一下是输出结果及程序;
Data Type Inital value
int 0
long 0
char
float 0.0
double 0.0
string null
short 0
boolean false
reference null
public class InitialValue {
int i;
long l;
char c;
short s;
float f;
double d;
boolean b;
String str;
InitialValue reference;
@Test
public void TestPirnt(){
System.out.println("Data Type Inital value ");
System.out.println(" int "+i);
System.out.println(" long "+l);
System.out.println(" char "+c);
System.out.println(" float "+f);
System.out.println(" double "+d);
System.out.println(" string "+str);
System.out.println(" short "+s);
System.out.println(" boolean "+b);
System.out.println(" reference "+reference);//引用类型
}
}
初始化顺序
类的数据成员初始化顺序,一下是程序和结果
windows{1}
windows{2}
windows{3}
house
windows{4}
fo
public class initializer {
public static void main(String[] args) {
house house = new house();
house.f();
}
}
class windows{
windows(int marker){
System.out.println("windows{"+marker+"}");
}
}
class house{
windows w1 = new windows(1);
house(){
System.out.println("house");
windows w4 = new windows(4);
}
windows w2 = new windows(2);
void f(){
System.out.println("fo");
}
windows w3 = new windows(3);
}
静态成员初始化顺序
静态数据成员在类当中只会初始化一次。
当类中既有实例对象,又有静态对象;在初始化时先初始化静态对象;当存在多个静态对象时,则按照位置的先后初始化;静态对象初始化完了以后,才去初始化实例对象,然后才会执行构造器(构造方法)里面的代码;
一下是实验程序运行结果和代码;
Bowl{1}
Bowl{2}
Table()
f1{1}
Bowl{4}
Bowl{5}
Bowl{3}
Cupboard()
f1{2}
Creating new Cupboard() in main()
Bowl{3}
Cupboard()
f1{2}
Creating new Cupboard() in main()
Bowl{3}
Cupboard()
f1{2}
f2{1}
f3{1}
public class staticInitalizer {
public static void main(String[] args) {
System.out.println("Creating new Cupboard() in main()");//10
new Cupboard();
System.out.println("Creating new Cupboard() in main()");//14
new Cupboard();
table.f2(1); //18
cupboard.f3(1); //19
}
static Table table= new Table();//先初始化静态成员变量
static Cupboard cupboard=new Cupboard();
}
class Bowl{
Bowl(int marker){
System.out.println("Bowl{"+marker+"}");
}
void f1(int marker){
System.out.println("f1{"+marker+"}");
}
}
class Table{
static Bowl bow1= new Bowl(1);//1
Table(){
System.out.println("Table()");//3
bow2.f1(1);//4
}
void f2(int marker){
System.out.println("f2{"+marker+"}");
}
static Bowl bow2 =new Bowl(2);//2
}
class Cupboard{
Bowl bow3 = new Bowl(3);//7 --11 --15
static Bowl bow4 = new Bowl(4);//5
Cupboard(){
System.out.println("Cupboard()");//8 --12 --16
bow4.f1(2);//9 --13 --17
}
void f3(int marker){
System.out.println("f3{"+marker+"}");
}
static Bowl bow5 = new Bowl(5);//6
}
Java构造器(构造方法)初始化问题
构造器返回当前的类,如果没有写构造器,java编译器会自动添加构造器;如果自己添加了构造器,java编译器则不会添加了
在java中初始化和创建是捆绑在一起,无法分离的;
构造器在new className();时自动调用
可以重载构造器,在new className();时根据参数的不同,编译器会自动匹配对应的构造器。
方法重载:重载方法时只能以方法名和参数列表来区分;不能以返回值类型来区分。
this关键字
直接在类中使用this 表示调用当前类;即对当前对象的引用
this可以在构造器中调用构造器