不創(chuàng)建show()方法,為什么也是可行的?不創(chuàng)建和創(chuàng)建有什么區(qū)別?
public class HelloWorld {
? ??
? ? String name; // 聲明變量name
String sex; //?聲明變量sex
static int age;// 聲明靜態(tài)變量age
? ??
? ? // 構(gòu)造方法
public ? HelloWorld ? ? () {?
System.out.println("通過構(gòu)造方法初始化name");
name = "tom";
}
? ??
? ? // 初始化塊
{?
System.out.println("通過初始化塊初始化sex");
sex = "男";
}
? ??
? ? // 靜態(tài)初始化塊
? ?static ? ?{?
System.out.println("通過靜態(tài)初始化塊初始化age");
age = 20;
}
? ??
? ??
public static void main(String[] args) {
? ? ? ??
? ? ? ? // 創(chuàng)建對象
HelloWorld hello = new HelloWorld();
// 調(diào)用對象的show方法
? ? ? ? System.out.println("姓名:"+hello.name+",性別:"+hello.sex+",年齡:"+age);
}
}
2016-11-29
不創(chuàng)建show()方法直接println是通過對象.屬性名直接調(diào)用你在HelloWorld類中的屬性(已賦值);
創(chuàng)建了show()方法是通過對象名.方法名調(diào)用里面的方法,相對于來說,創(chuàng)建方法比調(diào)用屬性更加方便,看起來也更加明了。
希望能幫助到你!