1.在构造器中设置值
2.在声明中赋值,这个太简单了,代码就不上了
3.显示域初始化
4.初始化块
补充知识:调用构造器的具体处理步骤
·所有数据域被初始化为默认值(0、false、null)
·按照在类声明中出现的次序,依次执行所有域初始化语句和初始化块
·如果构造器第一行调用了第二个构造器,则执行第二个构造器主体
·执行这个构造器的主题
see Core Java page125
/**
*
*/
package jry;
/**
* @author freewill
*
*/
public class InitFiledByConstructor {
int id;
String name;
public InitFiledByConstructor(int id, String name) {
this.id = id;
this.name = name;
}
public static void main(String[] args) {
InitFiledByConstructor a = new InitFiledByConstructor(23, "Jordan");
System.out.println(a.id + a.name);
}
}
2.在声明中赋值,这个太简单了,代码就不上了
3.显示域初始化
/**
*
*/
package jry;
/**
* @author freewill
* @desc 显示域初始化
* @see Java Core page122
*/
public class InitDemo {
static int nextId = 0;
int id = assignId();
static int assignId() {
int r = nextId;
nextId++;
return r;
}
/**
* @param args
* @desc Testcase
*/
public static void main(String[] args) {
System.out.println(new InitDemo().id);
System.out.println(new InitDemo().id);
}
}
4.初始化块
/**
*
*/
package jry;
/**
* @author freewill
* @desc 初始化块 Core Java page124
*/
public class InitFiledByBlock {
private static int nextId;
private int id;
private String name;
private double salary;
public InitFiledByBlock(String n, double s) {
this.name = n;
this.salary = s;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
{
id = nextId;
nextId++;
}
/**
* @param args
* @desc Testcase
*/
public static void main(String[] args) {
InitFiledByBlock c = new InitFiledByBlock("Jordan", 2300);
System.out.println(c.getId() + c.getName() + c.getSalary());
InitFiledByBlock d = new InitFiledByBlock("James", 2000);
System.out.println(d.getId() + d.getName() + d.getSalary());
}
}
补充知识:调用构造器的具体处理步骤
·所有数据域被初始化为默认值(0、false、null)
·按照在类声明中出现的次序,依次执行所有域初始化语句和初始化块
·如果构造器第一行调用了第二个构造器,则执行第二个构造器主体
·执行这个构造器的主题
see Core Java page125
本文介绍了Java中对象初始化的四种常见方法:通过构造器设置值、声明时直接赋值、使用初始化块以及显示域初始化,并提供了详细的代码示例。

310

被折叠的 条评论
为什么被折叠?



