類與對象:類是對一類事物的抽象定義(如「豬」),對象是具體實例(如「小白豬」)。對象引用(如變量 xiaoBai)指向堆內存中的對象。
public class Pig {
private int height, age;
void eat() { System.out.println("eat()"); }
void sleep() { System.out.println("sleep()"); }
public static void main(String[] args) {
Pig xiaoBai = new Pig();
Pig xiaoHei = new Pig();
xiaoBai.eat(); xiaoHei.sleep();
System.out.println(xiaoBai); // com.yq.Pig@74a14482
System.out.println(xiaoHei); // com.yq.Pig@1540e19d
System.out.println(xiaoBai == xiaoHei); // false
}
}
== 比較規則:
new String() 則在堆創建新對象String s1 = "java", s2 = "java"; // s1==s2 -> true
String str = new String("hello");
String str2 = "he" + new String("llo"); // str==str2 -> false,但 hashCode 相同
hashCode 相同不代表對象相同,String 的 hashCode 基於字符值計算。
<<(左移,低位補0),>>(右移,符號位擴展),>>>(無符號右移,高位補0)exp ? val1 : val2,可嵌套(type),向下轉型需強轉for 循環初始化/步進部分if-else、while、do-while、for、foreach、switchif 不加大括號默認僅管轄下一條語句else if 非關鍵字,實為 else { if ... }for(;;) 等同 while(true)foreach 適用於數組與實現 Iterable 的容器for (int i : arr) System.out.print(i + " "); for (String str : list) System.out.print(str + " ");
return:結束整個方法break:結束當前層循環continue:結束本次循環,進入下一次switch 選擇因子需為可生成 int 的表達式(含 char)this類成員自動初始化:數值 0、char '\0'、boolean false、引用 null。局部變量必須顯式初始化。
// 測試輸出驗證順序 Animal static -> Animal level:1 Pig static -> Pig level:2 Animal -> Animal constructor 2只眼睛 Pig -> Pig constructor
super(...) 顯式調用本質是編譯器自動封裝為數組:void test(String... args)
| 修飾符 | 同類 | 同包 | 子類 | 所有類 |
|---|---|---|---|---|
| private | ✓ | ✗ | ✗ | ✗ |
| default | ✓ | ✓ | ✗ | ✗ |
| protected | ✓ | ✓ | ✓ | ✗ |
| public | ✓ | ✓ | ✓ | ✓ |
類級別:一個文件最多一個 public 類,文件名須與之匹配。
private),複用功能而非接口通過動態綁定(後期綁定)實現:運行時根據對象實際類型調用方法。除 static/final/private 方法外,所有方法均為動態綁定。
public static void action(Animal anl) { anl.eat("蘋果"); }
action(new Pig()); // Pig eat():蘋果
action(new Cat()); // Cat eat():蘋果
新增動物類只需繼承 Animal,主程序無需修改,體現開閉原則。
public abstract;字段默認 public static final