1>概念:将对象引用置于新类中即可,不管是否是基本类型或引用类型
class WaterSource{
private String s;
WaterSource(){
System.out.println("WaterSource");
s = "Constructor";
}
@Override
public String toString() {
return s;
}
}
public class SprinklerSystem {
private String value1,value2,value3,value4;
//在定义的地方进行了初始化
private WaterSource source = new WaterSource();
private int i;
private float f;
@Override
public String toString() {
return "SprinklerSystem{" +
"value1='" + value1 + '\'' +
", value2='" + value2 + '\'' +
", value3='" + value3 + '\'' +
", value4='" + value4 + '\'' +
", source=" + source +
", i=" + i +
", f=" + f +
'}';
}
//在构建对象的时候 何时对组合的数据类型进行初始化,以及初始化的时候如何取值
public static void main(String[] args) {
final SprinklerSystem sprinklerSystem = new SprinklerSystem();
System.out.println(sprinklerSystem);
}
}
2>🤔思考:在何处对组合类型的数据进行初始化
- 在定义对象的地方。以为着这些对象总能够在构造器调用之前被初始化。
- 在类的构造器中。
- 在使用这些对象之前,这种形式成为惰性初始化。
使用实例初始化——————???????????
class Soap {
private String s;
Soap() {
System.out.println("Soap()");
s = "Constructed";
}
@Override
public String toString() {
return s;
}
}
public class Bath {
private String // 1,Initializing at point of definition:
s1 = "Happy",
s2 = "Happy",
s3,
s4;
private Soap castille;
private int i;
private float toy;
//2,在类的构造器中
public Bath() {
System.out.println("Inside Bath()");
s3 = "Joy";
toy = 3.14f;
castille = new Soap();
}
// 普通的代码块 称之为: 4,Instance initialization:(每次new的时候都会执行)
{
i = 47;
}
@Override
public String toString() {
if (s4 == null) // 3,Delayed initialization:
{
s4 = "Joy";
}
return
"s1 = " + s1 + "\n" +
"s2 = " + s2 + "\n" +
"s3 = " + s3 + "\n" +
"s4 = " + s4 + "\n" +
"i = " + i + "\n" +
"toy = " + toy + "\n" +
"castille = " + castille;
}
public static void main(String[] args) {
Bath b = new Bath();
System.out.println(b);
}
}
3>对实例初始化的理解,实例代码块(亦称为普通代码块);类比static代码块理解
public class InstanceInit {
String name;
//只会执行一次
static{
System.out.println("static 代码块");
//init();静态代码块中不能调用普通方法,
}
//普通的代码块 每次new的时候都会执行;代码块中亦可调用普通方法
{
name = "abc";
System.out.println(name+"===========");
init();
}
public void init(){
System.out.println("init");
}
public static void main(String[] args) {
InstanceInit instanceInit1 = new InstanceInit();
InstanceInit instanceInit2 = new InstanceInit();
InstanceInit instanceInit3 = new InstanceInit();
}
}