toString()方法
每一個非基本類型的對象都有一個toString()方法,當編譯器需要一個String而你卻只有一個對象時,該方法便會被調用。
class Sprink {
private String s;
private int value1;
private float value2;
Sprink(String s, int value1, float value2) {
this.s = s;
this.value1 = value1;
this.value2 = value2;
}
public String toString() {
return "s = " + s + " " + "value1 = " + value1 + " " + "value2 = " + value2;
}
}
public class Sprinkler {
public static void main(String[] args) {
Sprink sprink = new Sprink("spring",1,0.1f);
System.out.println(sprink);
}
}/*output
s = spring value1 = 1 value2 = 0.1
*/
在 System.out.println(sprink);中需要一個String對象,但是卻獲得了一個Sprink對象,這時編譯器就會自動調用toString(),把Sprink轉換成一個String。
初始化引用
編譯器不是簡單地爲每一個引用都創建默認對象,若想初始化這些引用有四種方法進行:
1、在類定義對象的地方,這意味着他們總是能夠在構造器被調用之前被初始化。
2、在類的構造器中。
3、就在正要使用這些對象之前,這種方式稱爲惰性初始化。
4、使用實例初始化。
class Soap {
private String s;
Soap() {
System.out.println("Soap()");
s = "Constructed";
}
public String toString() {return s;}
}
public class Bath {
private String
s1 = "Happy",
s2, s3;
private Soap castille;
private int i;
private float toy;
public Bath() {
System.out.println("Inside Bath()");
s2 = "Joy";
toy = 3.14f;
castille = new Soap();
}
{ i = 47; }
@Override
public String toString() {
return "Bath{" +
"s1='" + s1 + '\'' +
", s2='" + s2 + '\'' +
", s3='" + s3 + '\'' +
", castille=" + castille +
", i=" + i +
", toy=" + toy +
'}';
}
public static void main(String[] args) {
Bath b = new Bath();
System.out.println(b);
}
}/*output
Inside Bath()
Soap()
Bath{s1='Happy', s2='Joy', s3='Joy', castille=Constructed, i=47, toy=3.14}
*/
在這段代碼中s1是第一種初始化方法,castille、s2、toy是第二種,s3是第三種,i是第四種。
繼承與初始化
class Insect {
private int i = 9;
protected int j;
Insect() {
System.out.println("i = " + i + ", j = " + j);
j = 39;
}
private static int x1 = printInit("static Insect.x1 initialized");
static int printInit(String s) {
System.out.println(s);
return 47;
}
}
public class Beetle extends Insect {
private int k = printInit("Beetle.k initialized");
public Beetle() {
System.out.println("k = " + k);
System.out.println("j = " + j);
}
private static int x2 = printInit("static Beetle.x2 initialized");
public static void main(String[] args) {
System.out.println("Beetle constructor");
Beetle b = new Beetle();
}
}/*output
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
*/
運行Java時第一件事是訪問Beetle.main(),於是加載Beetle.class文件,在加載的過程中注意到它有一個基類,於是會先加載Insect.class,初始化靜態成員變量。當創建Beetle對象時,會先初始化基類的成員變量,執行基類的構造方法,然後初始化子類的成員變量,執行子類的構造方法。