1. 程式人生 > >Java實習生面試題整理

Java實習生面試題整理

一、資料型別

包裝型別

八個基本型別:

  • boolean/1
  • byte/8
  • char/16
  • short/16
  • int/32
  • float/32
  • long/64
  • double/64

基本型別都有對應的包裝型別,基本型別與其對應的包裝型別之間的賦值使用自動裝箱與拆箱完成。

Integer x = 2;     // 裝箱
int y = x;         // 拆箱

快取池

new Integer(123) 與 Integer.valueOf(123) 的區別在於:

  • new Integer(123) 每次都會新建一個物件
  • Integer.valueOf(123) 會使用快取池中的物件,多次呼叫會取得同一個物件的引用。
Integer x = new Integer(123);
Integer y = new Integer(123);
System.out.println(x == y);    // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(z == k);   // true

valueOf() 方法的實現比較簡單,就是先判斷值是否在快取池中,如果在的話就直接返回快取池的內容。

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

在 Java 8 中,Integer 快取池的大小預設為 -128~127。

static final int low = -128;
static final int high;
static final Integer cache[];

static {
    // high value may be configured by property
    int h = 127;
    String integerCacheHighPropValue =
        sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
    if (integerCacheHighPropValue != null) {
        try {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
        } catch( NumberFormatException nfe) {
            // If the property cannot be parsed into an int, ignore it.
        }
    }
    high = h;

    cache = new Integer[(high - low) + 1];
    int j = low;
    for(int k = 0; k < cache.length; k++)
        cache[k] = new Integer(j++);

    // range [-128, 127] must be interned (JLS7 5.1.7)
    assert IntegerCache.high >= 127;
}

編譯器會在自動裝箱過程呼叫 valueOf() 方法,因此多個 Integer 例項使用自動裝箱來建立並且值相同,那麼就會引用相同的物件。

Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true

基本型別對應的緩衝池如下:

  • boolean values true and false
  • all byte values
  • short values between -128 and 127
  • int values between -128 and 127
  • char in the range \u0000 to \u007F

在使用這些基本型別對應的包裝型別時,就可以直接使用緩衝池中的物件。

二、String

概覽

String 被宣告為 final,因此它不可被繼承。

內部使用 char 陣列儲存資料,該陣列被宣告為 final,這意味著 value 陣列初始化之後就不能再引用其它陣列。並且 String 內部沒有改變 value 陣列的方法,因此可以保證 String 不可變。

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

不可變的好處

1. 可以快取 hash 值

因為 String 的 hash 值經常被使用,例如 String 用做 HashMap 的 key。不可變的特性可以使得 hash 值也不可變,因此只需要進行一次計算。

2. String Pool 的需要

如果一個 String 物件已經被建立過了,那麼就會從 String Pool 中取得引用。只有 String 是不可變的,才可能使用 String Pool。

3. 安全性

String 經常作為引數,String 不可變性可以保證引數不可變。例如在作為網路連線引數的情況下如果 String 是可變的,那麼在網路連線過程中,String 被改變,改變 String 物件的那一方以為現在連線的是其它主機,而實際情況卻不一定是。

4. 執行緒安全

String 不可變性天生具備執行緒安全,可以在多個執行緒中安全地使用。

String, StringBuffer and StringBuilder

1. 可變性

  • String 不可變
  • StringBuffer 和 StringBuilder 可變

2. 執行緒安全

  • String 不可變,因此是執行緒安全的
  • StringBuilder 不是執行緒安全的
  • StringBuffer 是執行緒安全的,內部使用 synchronized 進行同步

String.intern()

使用 String.intern() 可以保證相同內容的字串變數引用同一的記憶體物件。

下面示例中,s1 和 s2 採用 new String() 的方式新建了兩個不同物件,而 s3 是通過 s1.intern() 方法取得一個物件引用。intern() 首先把 s1 引用的物件放到 String Pool(字串常量池)中,然後返回這個物件引用。因此 s3 和 s1 引用的是同一個字串常量池的物件。

String s1 = new String("aaa");
String s2 = new String("aaa");
System.out.println(s1 == s2);           // false
String s3 = s1.intern();
System.out.println(s1.intern() == s3);  // true

如果是採用 "bbb" 這種使用雙引號的形式建立字串例項,會自動地將新建的物件放入 String Pool 中。

String s4 = "bbb";
String s5 = "bbb";
System.out.println(s4 == s5);  // true

在 Java 7 之前,字串常量池被放在執行時常量池中,它屬於永久代。而在 Java 7,字串常量池被移到 Native Method 中。這是因為永久代的空間有限,在大量使用字串的場景下會導致 OutOfMemoryError 錯誤。

三、運算

引數傳遞

Java 的引數是以值傳遞的形式傳入方法中,而不是引用傳遞。

以下程式碼中 Dog dog 的 dog 是一個指標,儲存的是物件的地址。在將一個引數傳入一個方法時,本質上是將物件的地址以值的方式傳遞到形參中。因此在方法中改變指標引用的物件,那麼這兩個指標此時指向的是完全不同的物件,一方改變其所指向物件的內容對另一方沒有影響。

public class Dog {
    String name;

    Dog(String name) {
        this.name = name;
    }

    String getName() {
        return this.name;
    }

    void setName(String name) {
        this.name = name;
    }

    String getObjectAddress() {
        return super.toString();
    }
}
public class PassByValueExample {
    public static void main(String[] args) {
        Dog dog = new Dog("A");
        System.out.println(dog.getObjectAddress()); // [email protected]
        func(dog);
        System.out.println(dog.getObjectAddress()); // [email protected]
        System.out.println(dog.getName());          // A
    }

    private static void func(Dog dog) {
        System.out.println(dog.getObjectAddress()); // [email protected]
        dog = new Dog("B");
        System.out.println(dog.getObjectAddress()); // [email protected]
        System.out.println(dog.getName());          // B
    }
}

 但是如果在方法中改變物件的欄位值會改變原物件該欄位值,因為改變的是同一個地址指向的內容。

class PassByValueExample {
    public static void main(String[] args) {
        Dog dog = new Dog("A");
        func(dog);
        System.out.println(dog.getName());          // B
    }

    private static void func(Dog dog) {
        dog.setName("B");
    }
}

float 與 double

1.1 字面量屬於 double 型別,不能直接將 1.1 直接賦值給 float 變數,因為這是向下轉型。Java 不能隱式執行向下轉型,因為這會使得精度降低。

// float f = 1.1;

1.1f 字面量才是 float 型別。

float f = 1.1f;

隱式型別轉換

因為字面量 1 是 int 型別,它比 short 型別精度要高,因此不能隱式地將 int 型別下轉型為 short 型別。

short s1 = 1;
// s1 = s1 + 1;

但是使用 += 運算子可以執行隱式型別轉換。

s1 += 1;

上面的語句相當於將 s1 + 1 的計算結果進行了向下轉型:

s1 = (short) (s1 + 1);

switch

從 Java 7 開始,可以在 switch 條件判斷語句中使用 String 物件。

String s = "a";
switch (s) {
    case "a":
        System.out.println("aaa");
        break;
    case "b":
        System.out.println("bbb");
        break;
}

switch 不支援 long,是因為 switch 的設計初衷是對那些只有少數的幾個值進行等值判斷,如果值過於複雜,那麼還是用 if 比較合適。

// long x = 111;
// switch (x) { // Incompatible types. Found: 'long', required: 'char, byte, short, int, Character, Byte, Short, Integer, String, or an enum'
//     case 111:
//         System.out.println(111);
//         break;
//     case 222:
//         System.out.println(222);
//         break;
// }

四、繼承

訪問許可權

Java 中有三個訪問許可權修飾符:private、protected 以及 public,如果不加訪問修飾符,表示包級可見。

可以對類或類中的成員(欄位以及方法)加上訪問修飾符。

  • 類可見表示其它類可以用這個類建立例項物件。
  • 成員可見表示其它類可以用這個類的例項物件訪問到該成員;

protected 用於修飾成員,表示在繼承體系中成員對於子類可見,但是這個訪問修飾符對於類沒有意義。

設計良好的模組會隱藏所有的實現細節,把它的 API 與它的實現清晰地隔離開來。模組之間只通過它們的 API 進行通訊,一個模組不需要知道其他模組的內部工作情況,這個概念被稱為資訊隱藏或封裝。因此訪問許可權應當儘可能地使每個類或者成員不被外界訪問。

如果子類的方法重寫了父類的方法,那麼子類中該方法的訪問級別不允許低於父類的訪問級別。這是為了確保可以使用父類例項的地方都可以使用子類例項,也就是確保滿足里氏替換原則。

欄位決不能是公有的,因為這麼做的話就失去了對這個欄位修改行為的控制,客戶端可以對其隨意修改。例如下面的例子中,AccessExample 擁有 id 共有欄位,如果在某個時刻,我們想要使用 int 去儲存 id 欄位,那麼就需要去修改所有的客戶端程式碼。

public class AccessExample {
    public String id;
}

可以使用公有的 getter 和 setter 方法來替換公有欄位,這樣的話就可以控制對欄位的修改行為。

public class AccessExample {

    private int id;

    public String getId() {
        return id + "";
    }

    public void setId(String id) {
        this.id = Integer.valueOf(id);
    }
}

但是也有例外,如果是包級私有的類或者私有的巢狀類,那麼直接暴露成員不會有特別大的影響。

public class AccessWithInnerClassExample {
    private class InnerClass {
        int x;
    }

    private InnerClass innerClass;

    public AccessWithInnerClassExample() {
        innerClass = new InnerClass();
    }

    public int getValue() {
        return innerClass.x;  // 直接訪問
    }
}

抽象類與介面

1. 抽象類

抽象類和抽象方法都使用 abstract 關鍵字進行宣告。抽象類一般會包含抽象方法,抽象方法一定位於抽象類中。

抽象類和普通類最大的區別是,抽象類不能被例項化,需要繼承抽象類才能例項化其子類。

public abstract class AbstractClassExample {

    protected int x;
    private int y;

    public abstract void func1();

    public void func2() {
        System.out.println("func2");
    }
}
public class AbstractExtendClassExample extends AbstractClassExample {
    @Override
    public void func1() {
        System.out.println("func1");
    }
}
// AbstractClassExample ac1 = new AbstractClassExample(); // 'AbstractClassExample' is abstract; cannot be instantiated
AbstractClassExample ac2 = new AbstractExtendClassExample();
ac2.func1();

2. 介面

介面是抽象類的延伸,在 Java 8 之前,它可以看成是一個完全抽象的類,也就是說它不能有任何的方法實現。

從 Java 8 開始,介面也可以擁有預設的方法實現,這是因為不支援預設方法的介面的維護成本太高了。在 Java 8 之前,如果一個介面想要新增新的方法,那麼要修改所有實現了該介面的類。

介面的成員(欄位 + 方法)預設都是 public 的,並且不允許定義為 private 或者 protected。

介面的欄位預設都是 static 和 final 的。

public interface InterfaceExample {
    void func1();

    default void func2(){
        System.out.println("func2");
    }

    int x = 123;
    // int y;               // Variable 'y' might not have been initialized
    public int z = 0;       // Modifier 'public' is redundant for interface fields
    // private int k = 0;   // Modifier 'private' not allowed here
    // protected int l = 0; // Modifier 'protected' not allowed here
    // private void fun3(); // Modifier 'private' not allowed here
}
public class InterfaceImplementExample implements InterfaceExample {
    @Override
    public void func1() {
        System.out.println("func1");
    }
}
// InterfaceExample ie1 = new InterfaceExample(); // 'InterfaceExample' is abstract; cannot be instantiated
InterfaceExample ie2 = new InterfaceImplementExample();
ie2.func1();
System.out.println(InterfaceExample.x);

3. 比較

  • 從設計層面上看,抽象類提供了一種 IS-A 關係,那麼就必須滿足裡式替換原則,即子類物件必須能夠替換掉所有父類物件。而介面更像是一種 LIKE-A 關係,它只是提供一種方法實現契約,並不要求介面和實現介面的類具有 IS-A 關係。
  • 從使用上來看,一個類可以實現多個介面,但是不能繼承多個抽象類。
  • 介面的欄位只能是 static 和 final 型別的,而抽象類的欄位沒有這種限制。
  • 介面的成員只能是 public 的,而抽象類的成員可以有多種訪問許可權。

4. 使用選擇

使用介面:

  • 需要讓不相關的類都實現一個方法,例如不相關的類都可以實現 Compareable 介面中的 compareTo() 方法;
  • 需要使用多重繼承。

使用抽象類:

  • 需要在幾個相關的類中共享程式碼。
  • 需要能控制繼承來的成員的訪問許可權,而不是都為 public。
  • 需要繼承非靜態和非常量欄位。

在很多情況下,介面優先於抽象類,因為介面沒有抽象類嚴格的類層次結構要求,可以靈活地為一個類新增行為。並且從 Java 8 開始,介面也可以有預設的方法實現,使得修改介面的成本也變的很低。

super

  • 訪問父類的建構函式:可以使用 super() 函式訪問父類的建構函式,從而委託父類完成一些初始化的工作。
  • 訪問父類的成員:如果子類重寫了父類的中某個方法的實現,可以通過使用 super 關鍵字來引用父類的方法實現。
public class SuperExample {
    protected int x;
    protected int y;

    public SuperExample(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void func() {
        System.out.println("SuperExample.func()");
    }
}
public class SuperExtendExample extends SuperExample {
    private int z;

    public SuperExtendExample(int x, int y, int z) {
        super(x, y);
        this.z = z;
    }

    @Override
    public void func() {
        super.func();
        System.out.println("SuperExtendExample.func()");
    }
}
SuperExample e = new SuperExtendExample(1, 2, 3);
e.func();
SuperExample.func()
SuperExtendExample.func()

重寫與過載

1. 重寫(Override)

存在於繼承體系中,指子類實現了一個與父類在方法宣告上完全相同的一個方法。

為了滿足裡式替換原則,重寫有有以下兩個限制:

  • 子類方法的訪問許可權必須大於等於父類方法;
  • 子類方法的返回型別必須是父類方法返回型別或為其子型別。

使用 @Override 註解,可以讓編譯器幫忙檢查是否滿足上面的兩個限制條件。

2. 過載(Overload)

存在於同一個類中,指一個方法與已經存在的方法名稱上相同,但是引數型別、個數、順序至少有一個不同。

應該注意的是,返回值不同,其它都相同不算是過載。

五、Object 通用方法

概覽

public final native Class<?> getClass()

public native int hashCode()

public boolean equals(Object obj)

protected native Object clone() throws CloneNotSupportedException

public String toString()

public final native void notify()

public final native void notifyAll()

public final native void wait(long timeout) throws InterruptedException

public final void wait(long timeout, int nanos) throws InterruptedException

public final void wait() throws InterruptedException

protected void finalize() throws Throwable {}

equals()

1. 等價關係

(一)自反性

x.equals(x); // true

(二)對稱性

x.equals(y) == y.equals(x); // true

(三)傳遞性

if (x.equals(y) && y.equals(z))
    x.equals(z); // true;

(四)一致性

多次呼叫 equals() 方法結果不變

x.equals(y) == x.equals(y); // true

(五)與 null 的比較

對任何不是 null 的物件 x 呼叫 x.equals(null) 結果都為 false

x.equals(null); // false;

2. equals() 與 ==

  • 對於基本型別,== 判斷兩個值是否相等,基本型別沒有 equals() 方法。
  • 對於引用型別,== 判斷兩個變數是否引用同一個物件,而 equals() 判斷引用的物件是否等價。
Integer x = new Integer(1);
Integer y = new Integer(1);
System.out.println(x.equals(y)); // true
System.out.println(x == y);      // false

3. 實現

  • 檢查是否為同一個物件的引用,如果是直接返回 true;
  • 檢查是否是同一個型別,如果不是,直接返回 false;
  • 將 Object 物件進行轉型;
  • 判斷每個關鍵域是否相等。
public class EqualExample {
    private int x;
    private int y;
    private int z;

    public EqualExample(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        EqualExample that = (EqualExample) o;

        if (x != that.x) return false;
        if (y != that.y) return false;
        return z == that.z;
    }
}

hashCode()

hasCode() 返回雜湊值,而 equals() 是用來判斷兩個物件是否等價。等價的兩個物件雜湊值一定相同,但是雜湊值相同的兩個物件不一定等價。

在覆蓋 equals() 方法時應當總是覆蓋 hashCode() 方法,保證等價的兩個物件雜湊值也相等。

下面的程式碼中,新建了兩個等價的物件,並將它們新增到 HashSet 中。我們希望將這兩個物件當成一樣的,只在集合中新增一個物件,但是因為 EqualExample 沒有實現 hasCode() 方法,因此這兩個物件的雜湊值是不同的,最終導致集合添加了兩個等價的物件。

EqualExample e1 = new EqualExample(1, 1, 1);
EqualExample e2 = new EqualExample(1, 1, 1);
System.out.println(e1.equals(e2)); // true
HashSet<EqualExample> set = new HashSet<>();
set.add(e1);
set.add(e2);
System.out.println(set.size());   // 2

理想的雜湊函式應當具有均勻性,即不相等的物件應當均勻分佈到所有可能的雜湊值上。這就要求了雜湊函式要把所有域的值都考慮進來,可以將每個域都當成 R 進位制的某一位,然後組成一個 R 進位制的整數。R 一般取 31,因為它是一個奇素數,如果是偶數的話,當出現乘法溢位,資訊就會丟失,因為與 2 相乘相當於向左移一位。

一個數與 31 相乘可以轉換成移位和減法:31*x == (x<<5)-x,編譯器會自動進行這個優化。

@Override
public int hashCode() {
    int result = 17;
    result = 31 * result + x;
    result = 31 * result + y;
    result = 31 * result + z;
    return result;
}

toString()

預設返回 [email protected] 這種形式,其中 @ 後面的數值為雜湊碼的無符號十六進位制表示。

public class ToStringExample {
    private int number;

    public ToStringExample(int number) {
        this.number = number;
    }
}
ToStringExample example = new ToStringExample(123);
System.out.println(example.toString());
[email protected]

clone()

1. cloneable

clone() 是 Object 的 protected 方法,它不是 public,一個類不顯式去重寫 clone(),其它類就不能直接去呼叫該類例項的 clone() 方法。

public class CloneExample {
    private int a;
    private int b;
}
CloneExample e1 = new CloneExample();
// CloneExample e2 = e1.clone(); // 'clone()' has protected access in 'java.lang.Object'

重寫 clone() 得到以下實現:

public class CloneExample {
    private int a;
    private int b;

    @Override
    protected CloneExample clone() throws CloneNotSupportedException {
        return (CloneExample)super.clone();
    }
}
CloneExample e1 = new CloneExample();
try {
    CloneExample e2 = e1.clone();
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}
java.lang.CloneNotSupportedException: CloneExample

以上丟擲了 CloneNotSupportedException,這是因為 CloneExample 沒有實現 Cloneable 介面。

應該注意的是,clone() 方法並不是 Cloneable 介面的方法,而是 Object 的一個 protected 方法。Cloneable 介面只是規定,如果一個類沒有實現 Cloneable 介面又呼叫了 clone() 方法,就會丟擲 CloneNotSupportedException。

public class CloneExample implements Cloneable {
    private int a;
    private int b;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

2. 淺拷貝

拷貝物件和原始物件的引用型別引用同一個物件。

public class ShallowCloneExample implements Cloneable {
    private int[] arr;

    public ShallowCloneExample() {
        arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
    }

    public void set(int index, int value) {
        arr[index] = value;
    }

    public int get(int index) {
        return arr[index];
    }

    @Override
    protected ShallowCloneExample clone() throws CloneNotSupportedException {
        return (ShallowCloneExample) super.clone();
    }
}
ShallowCloneExample e1 = new ShallowCloneExample();
ShallowCloneExample e2 = null;
try {
    e2 = e1.clone();
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}
e1.set(2, 222);
System.out.println(e2.get(2)); // 222

 3. 深拷貝

拷貝物件和原始物件的引用型別引用不同物件。

public class DeepCloneExample implements Cloneable {
    private int[] arr;

    public DeepCloneExample() {
        arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
    }

    public void set(int index, int value) {
        arr[index] = value;
    }

    public int get(int index) {
        return arr[index];
    }

    @Override
    protected DeepCloneExample clone() throws CloneNotSupportedException {
        DeepCloneExample result = (DeepCloneExample) super.clone();
        result.arr = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            result.arr[i] = arr[i];
        }
        return result;
    }
}
DeepCloneExample e1 = new DeepCloneExample();
DeepCloneExample e2 = null;
try {
    e2 = e1.clone();
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}
e1.set(2, 222);
System.out.println(e2.get(2)); // 2

 4. clone() 的替代方案

使用 clone() 方法來拷貝一個物件即複雜又有風險,它會丟擲異常,並且還需要型別轉換。Effective Java 書上講到,最好不要去使用 clone(),可以使用拷貝建構函式或者拷貝工廠來拷貝一個物件。

public class CloneConstructorExample {
    private int[] arr;

    public CloneConstructorExample() {
        arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
    }

    public CloneConstructorExample(CloneConstructorExample original) {
        arr = new int[original.arr.length];
        for (int i = 0; i < original.arr.length; i++) {
            arr[i] = original.arr[i];
        }
    }

    public void set(int index, int value) {
        arr[index] = value;
    }

    public int get(int index) {
        return arr[index];
    }
}
CloneConstructorExample e1 = new CloneConstructorExample();
CloneConstructorExample e2 = new CloneConstructorExample(e1);
e1.set(2, 222);
System.out.println(e2.get(2)); // 2

六、關鍵字

final

1. 資料

宣告資料為常量,可以是編譯時常量,也可以是在執行時被初始化後不能被改變的常量。

  • 對於基本型別,final 使數值不變;
  • 對於引用型別,final 使引用不變,也就不能引用其它物件,但是被引用的物件本身是可以修改的。
final int x = 1;
// x = 2;  // cannot assign value to final variable 'x'
final A y = new A();
y.a = 1;

2. 方法

宣告方法不能被子類重寫。

private 方法隱式地被指定為 final,如果在子類中定義的方法和基類中的一個 private 方法簽名相同,此時子類的方法不是重寫基類方法,而是在子類中定義了一個新的方法。

3. 類

宣告類不允許被繼承。

static

1. 靜態變數

  • 靜態變數:又稱為類變數,也就是說這個變數屬於類的,類所有的例項都共享靜態變數,可以直接通過類名來訪問它;靜態變數在記憶體中只存在一份。
  • 例項變數:每建立一個例項就會產生一個例項變數,它與該例項同生共死。
public class A {
    private int x;         // 例項變數
    private static int y;  // 靜態變數

    public static void main(String[] args) {
        // int x = A.x;  // Non-static field 'x' cannot be referenced from a static context
        A a = new A();
        int x = a.x;
        int y = A.y;
    }
}

2. 靜態方法

靜態方法在類載入的時候就存在了,它不依賴於任何例項。所以靜態方法必須有實現,也就是說它不能是抽象方法(abstract)。

public abstract class A {
    public static void func1(){
    }
    // public abstract static void func2();  // Illegal combination of modifiers: 'abstract' and 'static'
}

只能訪問所屬類的靜態欄位和靜態方法,方法中不能有 this 和 super 關鍵字。

public class A {
    private static int x;
    private int y;

    public static void func1(){
        int a = x;
        // int b = y;  // Non-static field 'y' cannot be referenced from a static context
        // int b = this.y;     // 'A.this' cannot be referenced from a static context
    }
}

3. 靜態語句塊

靜態語句塊在類初始化時執行一次。

public class A {
    static {
        System.out.println("123");
    }

    public static void main(String[] args) {
        A a1 = new A();
        A a2 = new A();
    }
}
123

4. 靜態內部類

非靜態內部類依賴於外部類的例項,而靜態內部類不需要。

public class OuterClass {
    class InnerClass {
    }

    static class StaticInnerClass {
    }

    public static void main(String[] args) {
        // InnerClass innerClass = new InnerClass(); // 'OuterClass.this' cannot be referenced from a static context
        OuterClass outerClass = new OuterClass();
        InnerClass innerClass = outerClass.new InnerClass();
        StaticInnerClass staticInnerClass = new StaticInnerClass();
    }
}

靜態內部類不能訪問外部類的非靜態的變數和方法。

5. 靜態導包

在使用靜態變數和方法時不用再指明 ClassName,從而簡化程式碼,但可讀性大大降低。

import static com.xxx.ClassName.*

6. 初始化順序

靜態變數和靜態語句塊優先於例項變數和普通語句塊,靜態變數和靜態語句塊的初始化順序取決於它們在程式碼中的順序。

public static String staticField = "靜態變數";
static {
    System.out.println("靜態語句塊");
}
public String field = "例項變數";
{
    System.out.println("普通語句塊");
}

最後才是建構函式的初始化。

public InitialOrderTest() {
    System.out.println("建構函式");
}

存在繼承的情況下,初始化順序為:

  • 父類(靜態變數、靜態語句塊)
  • 子類(靜態變數、靜態語句塊)
  • 父類(例項變數、普通語句塊)
  • 父類(建構函式)
  • 子類(例項變數、普通語句塊)
  • 子類(建構函式)

七、反射

每個類都有一個 Class 物件,包含了與類有關的資訊。當編譯一個新類時,會產生一個同名的 .class 檔案,該檔案內容儲存著 Class 物件。

類載入相當於 Class 物件的載入。類在第一次使用時才動態載入到 JVM 中,可以使用 Class.forName("com.mysql.jdbc.Driver") 這種方式來控制類的載入,該方法會返回一個 Class 物件。

反射可以提供執行時的類資訊,並且這個類可以在執行時才載入進來,甚至在編譯時期該類的 .class 不存在也可以載入進來。

Class 和 java.lang.reflect 一起對反射提供了支援,java.lang.reflect 類庫主要包含了以下三個類:

  • Field :可以使用 get() 和 set() 方法讀取和修改 Field 物件關聯的欄位;
  • Method :可以使用 invoke() 方法呼叫與 Method 物件關聯的方法;
  • Constructor :可以用 Constructor 建立新的物件。

Advantages of Using Reflection:

  • Extensibility Features : An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
  • Class Browsers and Visual Development Environments : A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code.
  • Debuggers and Test Tools : Debuggers need to be able to examine private members on classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

Drawbacks of Reflection:

Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

  • Performance Overhead : Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

  • Security Restrictions : Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

  • Exposure of Internals :Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

八、異常

Throwable 可以用來表示任何可以作為異常丟擲的類,分為兩種: Error 和 Exception。其中 Error 用來表示 JVM 無法處理的錯誤,Exception 分為兩種:

  • 受檢異常 :需要用 try...catch... 語句捕獲並進行處理,並且可以從異常中恢復;
  • 非受檢異常 :是程式執行時錯誤,例如除 0 會引發 Arithmetic Exception,此時程式崩潰並且無法恢復。

九、泛型

public class Box<T> {
    // T stands for "Type"
    private T t;
    public void set(T t) { this.t = t; }
    public T get() { return t; }
}

十、註解

Java 註解是附加在程式碼中的一些元資訊,用於一些工具在編譯、執行時進行解析和使用,起到說明、配置的功能。註解不會也不能影響程式碼的實際邏輯,僅僅起到輔助性的作用。

十一、特性

Java 各版本的新特性

New highlights in Java SE 8

  1. Lambda Expressions
  2. Pipelines and Streams
  3. Date and Time API
  4. Default Methods
  5. Type Annotations
  6. Nashhorn JavaScript Engine
  7. Concurrent Accumulators
  8. Parallel operations
  9. PermGen Error Removed

New highlights in Java SE 7

  1. Strings in Switch Statement
  2. Type Inference for Generic Instance Creation
  3. Multiple Exception Handling
  4. Support for Dynamic Languages
  5. Try with Resources
  6. Java nio Package
  7. Binary Literals, Underscore in literals
  8. Diamond Syntax

Java 與 C++ 的區別

  • Java 是純粹的面嚮物件語言,所有的物件都繼承自 java.lang.Object,C++ 為了相容 C 即支援面向物件也支援面向過程。
  • Java 通過虛擬機器從而實現跨平臺特性,但是 C++ 依賴於特定的平臺。
  • Java 沒有指標,它的引用可以理解為安全指標,而 C++ 具有和 C 一樣的指標。
  • Java 支援自動垃圾回收,而 C++ 需要手動回收。
  • Java 不支援多重繼承,只能通過實現多個介面來達到相同目的,而 C++ 支援多重繼承。
  • Java 不支援操作符過載,雖然可以對兩個 String 物件支援加法運算,但是這是語言內建支援的操作,不屬於操作符過載,而 C++ 可以。
  • Java 的 goto 是保留字,但是不可用,C++ 可以使用 goto。
  • Java 不支援條件編譯,C++ 通過 #ifdef #ifndef 等預處理命令從而實現條件編譯。

JRE or JDK

  • JRE is the JVM program, Java application need to run on JRE.
  • JDK is a superset of JRE, JRE + tools for developing java programs. e.g, it provides the compiler "javac"

參考資料

  • Eckel B. Java 程式設計思想[M]. 機械工業出版社, 2002.
  • Bloch J. Effective java[M]. Addison-Wesley Professional, 2017.

我有一個微信公眾號,經常會分享一些Java技術相關的乾貨;如果你喜歡我的分享,可以用微信搜尋“Java團長”或者“javatuanzhang”關注。