包的推薦命名規則:java
Tips:類中的成員屬性默認有初始值測試
基本類型 | 默認值 |
---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0 |
char | 'u0000' |
boolean | false |
引用類型 | null |
實例化對象的過程能夠分紅兩個部分:this
構造方法結構:設計
public 構造方法名(參數列表){ 初始代碼塊; }
this關鍵字的使用:code
this(參數列表);
調用構造方法,this(參數列表);
必須放在方法體內的第一行 vio對象
package Chapter9.Lecture1.cat; /** * 寵物貓類 */ public class Cat { //成員屬性:暱稱、年齡、體重、品種 String name; //暱稱,String類型默認值爲null int month; //年齡,int類型默認值爲0 double weight; //體重,double類型默認值爲0.0 String species; //品種 //無參構造方法 public Cat() { System.out.println("我是無參構造方法"); } //帶參構造方法 public Cat(String name, int month, double weight, String species) { this.name = name; this.month = month; this.weight = weight; this.species = species; } //成員行爲:跑動、吃東西 //跑動的方法 public void run() { System.out.println("小貓快跑"); } public void run(String name) { System.out.println(name + "快跑"); } //吃東西的方法 public void eat() { System.out.println("小貓吃魚"); } }
package Chapter9.Lecture1.cat; public class CatTest { public static void main(String[] args) { //對象實例化 Cat one = new Cat(); //測試 one.eat(); one.run(); System.out.println("=================="); one.name = "花花"; one.month = 2; one.weight = 1000; one.species = "英國短毛貓"; System.out.println("暱稱:" + one.name); System.out.println("年齡:" + one.month); System.out.println("體重:" + one.weight); System.out.println("品種:" + one.species); System.out.println("=================="); one.run(one.name); } }