Java 基础.md 40.3 KB
Newer Older
C
CyC2018 已提交
1
<!-- GFM-TOC -->
C
CyC2018 已提交
2
* [一、数据类型](#一数据类型)
C
CyC2018 已提交
3 4 5
    * [包装类型](#包装类型)
    * [缓存池](#缓存池)
* [二、String](#二string)
C
CyC2018 已提交
6
    * [概览](#概览)
C
CyC2018 已提交
7
    * [不可变的好处](#不可变的好处)
C
CyC2018 已提交
8
    * [String, StringBuffer and StringBuilder](#string,-stringbuffer-and-stringbuilder)
C
CyC2018 已提交
9 10
    * [String Pool](#string-pool)
    * [new String("abc")](#new-string"abc")
C
CyC2018 已提交
11 12 13 14 15
* [三、运算](#三运算)
    * [参数传递](#参数传递)
    * [float 与 double](#float-与-double)
    * [隐式类型转换](#隐式类型转换)
    * [switch](#switch)
C
CyC2018 已提交
16 17 18 19
* [四、继承](#四继承)
    * [访问权限](#访问权限)
    * [抽象类与接口](#抽象类与接口)
    * [super](#super)
C
CyC2018 已提交
20
    * [重写与重载](#重写与重载)
C
CyC2018 已提交
21 22 23 24 25 26 27 28 29
* [五、Object 通用方法](#五object-通用方法)
    * [概览](#概览)
    * [equals()](#equals)
    * [hashCode()](#hashcode)
    * [toString()](#tostring)
    * [clone()](#clone)
* [六、关键字](#六关键字)
    * [final](#final)
    * [static](#static)
C
CyC2018 已提交
30 31 32 33 34 35 36 37 38 39 40 41
* [七、反射](#七反射)
* [八、异常](#八异常)
* [九、泛型](#九泛型)
* [十、注解](#十注解)
* [十一、特性](#十一特性)
    * [Java 各版本的新特性](#java-各版本的新特性)
    * [Java 与 C++ 的区别](#java-与-c-的区别)
    * [JRE or JDK](#jre-or-jdk)
* [参考资料](#参考资料)
<!-- GFM-TOC -->


C
CyC2018 已提交
42
# 一、数据类型
C
CyC2018 已提交
43

C
CyC2018 已提交
44
## 包装类型
C
CyC2018 已提交
45

C
CyC2018 已提交
46
八个基本类型:
C
CyC2018 已提交
47

C
CyC2018 已提交
48 49 50 51 52 53 54 55
- boolean/1
- byte/8
- char/16
- short/16
- int/32
- float/32
- long/64
- double/64
C
CyC2018 已提交
56

C
CyC2018 已提交
57
基本类型都有对应的包装类型,基本类型与其对应的包装类型之间的赋值使用自动装箱与拆箱完成。
C
CyC2018 已提交
58 59

```java
C
CyC2018 已提交
60 61
Integer x = 2;     // 装箱
int y = x;         // 拆箱
C
CyC2018 已提交
62 63
```

C
CyC2018 已提交
64 65
## 缓存池

C
CyC2018 已提交
66 67
new Integer(123) 与 Integer.valueOf(123) 的区别在于:

C
CyC2018 已提交
68
- new Integer(123) 每次都会新建一个对象;
C
CyC2018 已提交
69
- Integer.valueOf(123) 会使用缓存池中的对象,多次调用会取得同一个对象的引用。
C
CyC2018 已提交
70 71 72 73 74 75 76 77 78

```java
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
```
C
CyC2018 已提交
79

C
CyC2018 已提交
80
valueOf() 方法的实现比较简单,就是先判断值是否在缓存池中,如果在的话就直接返回缓存池的内容。
C
CyC2018 已提交
81

C
CyC2018 已提交
82 83 84 85 86 87 88
```java
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
```
C
CyC2018 已提交
89

C
CyC2018 已提交
90
在 Java 8 中,Integer 缓存池的大小默认为 -128\~127。
C
CyC2018 已提交
91

C
CyC2018 已提交
92 93 94 95
```java
static final int low = -128;
static final int high;
static final Integer cache[];
C
CyC2018 已提交
96

C
CyC2018 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
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;
C
CyC2018 已提交
113

C
CyC2018 已提交
114 115 116 117 118 119 120 121 122 123
    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;
}
```

C
CyC2018 已提交
124 125 126 127 128 129 130 131 132
编译器会在自动装箱过程调用 valueOf() 方法,因此多个 Integer 实例使用自动装箱来创建并且值相同,那么就会引用相同的对象。

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

基本类型对应的缓冲池如下:
C
CyC2018 已提交
133 134 135 136 137 138 139

- 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

C
CyC2018 已提交
140
在使用这些基本类型对应的包装类型时,就可以直接使用缓冲池中的对象。
C
CyC2018 已提交
141 142 143 144 145 146 147 148 149 150

[StackOverflow : Differences between new Integer(123), Integer.valueOf(123) and just 123
](https://stackoverflow.com/questions/9030817/differences-between-new-integer123-integer-valueof123-and-just-123)

# 二、String

## 概览

String 被声明为 final,因此它不可被继承。

C
CyC2018 已提交
151
内部使用 char 数组存储数据,该数组被声明为 final,这意味着 value 数组初始化之后就不能再引用其它数组。并且 String 内部没有改变 value 数组的方法,因此可以保证 String 不可变。
C
CyC2018 已提交
152 153

```java
C
CyC2018 已提交
154 155 156 157 158 159
public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
```

C
CyC2018 已提交
160
## 不可变的好处
C
CyC2018 已提交
161 162 163 164 165 166 167 168 169

**1. 可以缓存 hash 值** 

因为 String 的 hash 值经常被使用,例如 String 用做 HashMap 的 key。不可变的特性可以使得 hash 值也不可变,因此只需要进行一次计算。

**2. String Pool 的需要** 

如果一个 String 对象已经被创建过了,那么就会从 String Pool 中取得引用。只有 String 是不可变的,才可能使用 String Pool。

C
fix  
CyC2018 已提交
170
<div align="center"> <img src="pics/f76067a5-7d5f-4135-9549-8199c77d8f1c.jpg" width=""/> </div><br>
C
CyC2018 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

**3. 安全性** 

String 经常作为参数,String 不可变性可以保证参数不可变。例如在作为网络连接参数的情况下如果 String 是可变的,那么在网络连接过程中,String 被改变,改变 String 对象的那一方以为现在连接的是其它主机,而实际情况却不一定是。

**4. 线程安全** 

String 不可变性天生具备线程安全,可以在多个线程中安全地使用。

[Program Creek : Why String is immutable in Java?](https://www.programcreek.com/2013/04/why-string-is-immutable-in-java/)

## String, StringBuffer and StringBuilder

**1. 可变性** 

- String 不可变
- StringBuffer 和 StringBuilder 可变

**2. 线程安全** 

- String 不可变,因此是线程安全的
- StringBuilder 不是线程安全的
C
CyC2018 已提交
193
- StringBuffer 是线程安全的,内部使用 synchronized 进行同步
C
CyC2018 已提交
194 195 196

[StackOverflow : String, StringBuffer, and StringBuilder](https://stackoverflow.com/questions/2971315/string-stringbuffer-and-stringbuilder)

C
CyC2018 已提交
197
## String Pool
C
CyC2018 已提交
198

C
CyC2018 已提交
199
字符串常量池(String Pool)保存着所有字符串字面量(literal strings),这些字面量在编译时期就确定。不仅如此,还可以使用 String 的 intern() 方法在运行过程中将字符串添加到 String Pool 中。
C
CyC2018 已提交
200

C
CyC2018 已提交
201
当一个字符串调用 intern() 方法时,如果 String Pool 中已经存在一个字符串和该字符串值相等(使用 equals() 方法进行确定),那么就会返回 String Pool 中字符串的引用;否则,就会在 String Pool 中添加一个新的字符串,并返回这个新字符串的引用。
C
CyC2018 已提交
202 203

下面示例中,s1 和 s2 采用 new String() 的方式新建了两个不同字符串,而 s3 和 s4 是通过 s1.intern() 方法取得一个字符串引用。intern() 首先把 s1 引用的字符串放到 String Pool 中,然后返回这个字符串引用。因此 s3 和 s4 引用的是同一个字符串。
C
CyC2018 已提交
204 205 206 207 208 209

```java
String s1 = new String("aaa");
String s2 = new String("aaa");
System.out.println(s1 == s2);           // false
String s3 = s1.intern();
C
CyC2018 已提交
210 211
String s4 = s1.intern();
System.out.println(s3 == s4);           // true
C
CyC2018 已提交
212 213
```

C
CyC2018 已提交
214
如果是采用 "bbb" 这种字面量的形式创建字符串,会自动地将字符串放入 String Pool 中。
C
CyC2018 已提交
215 216 217

```java
String s5 = "bbb";
C
CyC2018 已提交
218
String s6 = "bbb";
C
CyC2018 已提交
219
System.out.println(s5 == s6);  // true
C
CyC2018 已提交
220 221
```

C
CyC2018 已提交
222
在 Java 7 之前,String Pool 被放在运行时常量池中,它属于永久代。而在 Java 7,String Pool 被移到堆中。这是因为永久代的空间有限,在大量使用字符串的场景下会导致 OutOfMemoryError 错误。
C
CyC2018 已提交
223

C
CyC2018 已提交
224
- [StackOverflow : What is String interning?](https://stackoverflow.com/questions/10578984/what-is-string-interning)
C
CyC2018 已提交
225 226
- [深入解析 String#intern](https://tech.meituan.com/in_depth_understanding_string_intern.html)

C
CyC2018 已提交
227 228
## new String("abc")

C
CyC2018 已提交
229
使用这种方式一共会创建两个字符串对象(前提是 String Pool 中还没有 "abc" 字符串对象)。
C
CyC2018 已提交
230

C
CyC2018 已提交
231
- "abc" 属于字符串字面量,因此编译时期会在 String Pool 中创建一个字符串对象,指向这个 "abc" 字符串字面量;
C
CyC2018 已提交
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
- 而使用 new 的方式会在堆中创建一个字符串对象。

创建一个测试类,其 main 方法中使用这种方式来创建字符串对象。

```java
public class NewStringTest {
    public static void main(String[] args) {
        String s = new String("abc");
    }
}
```

使用 javap -verbose 进行反编译,得到以下内容:

```java
// ...
Constant pool:
// ...
   #2 = Class              #18            // java/lang/String
   #3 = String             #19            // abc
// ...
  #18 = Utf8               java/lang/String
  #19 = Utf8               abc
// ...

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=3, locals=2, args_size=1
         0: new           #2                  // class java/lang/String
         3: dup
         4: ldc           #3                  // String abc
         6: invokespecial #4                  // Method java/lang/String."<init>":(Ljava/lang/String;)V
         9: astore_1
// ...
```

C
CyC2018 已提交
270
在 Constant Pool 中,#19 存储这字符串字面量 "abc",#3 是 String Pool 的字符串对象,它指向 #19 这个字符串字面量。在 main 方法中,0: 行使用 new #2 在堆中创建一个字符串对象,并且使用 ldc #3 将 String Pool 中的字符串对象作为 String 构造函数的参数。
C
CyC2018 已提交
271 272 273 274 275 276 277 278 279 280

以下是 String 构造函数的源码,可以看到,在将一个字符串对象作为另一个字符串对象的构造函数参数时,并不会完全复制 value 数组内容,而是都会指向同一个 value 数组。

```java
public String(String original) {
    this.value = original.value;
    this.hash = original.hash;
}
```

C
CyC2018 已提交
281 282 283 284 285 286
# 三、运算

## 参数传递

Java 的参数是以值传递的形式传入方法中,而不是引用传递。

C
CyC2018 已提交
287
以下代码中 Dog dog 的 dog 是一个指针,存储的是对象的地址。在将一个参数传入一个方法时,本质上是将对象的地址以值的方式传递到形参中。因此在方法中使指针引用其它对象,那么这两个指针此时指向的是完全不同的对象,在一方改变其所指向对象的内容时对另一方没有影响。
C
CyC2018 已提交
288 289 290

```java
public class Dog {
C
CyC2018 已提交
291

C
CyC2018 已提交
292 293 294 295 296 297 298
    String name;

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

    String getName() {
C
CyC2018 已提交
299 300 301 302 303
        return this.name;
    }

    void setName(String name) {
        this.name = name;
C
CyC2018 已提交
304 305 306 307 308
    }

    String getObjectAddress() {
        return super.toString();
    }
C
CyC2018 已提交
309 310 311
}
```

C
CyC2018 已提交
312 313 314 315 316 317 318 319 320
```java
public class PassByValueExample {
    public static void main(String[] args) {
        Dog dog = new Dog("A");
        System.out.println(dog.getObjectAddress()); // Dog@4554617c
        func(dog);
        System.out.println(dog.getObjectAddress()); // Dog@4554617c
        System.out.println(dog.getName());          // A
    }
C
CyC2018 已提交
321

C
CyC2018 已提交
322 323 324 325 326 327 328 329
    private static void func(Dog dog) {
        System.out.println(dog.getObjectAddress()); // Dog@4554617c
        dog = new Dog("B");
        System.out.println(dog.getObjectAddress()); // Dog@74a14482
        System.out.println(dog.getName());          // B
    }
}
```
C
CyC2018 已提交
330

C
CyC2018 已提交
331
如果在方法中改变对象的字段值会改变原对象该字段值,因为改变的是同一个地址指向的内容。
C
CyC2018 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

```java
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");
    }
}
```

C
CyC2018 已提交
347
[StackOverflow: Is Java “pass-by-reference” or “pass-by-value”?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value)
C
CyC2018 已提交
348

C
CyC2018 已提交
349
## float 与 double
C
CyC2018 已提交
350

C
CyC2018 已提交
351 352 353
Java 不能隐式执行向下转型,因为这会使得精度降低。

1.1 字面量属于 double 类型,不能直接将 1.1 直接赋值给 float 变量,因为这是向下转型。
C
CyC2018 已提交
354

C
CyC2018 已提交
355 356 357
```java
// float f = 1.1;
```
C
CyC2018 已提交
358

C
CyC2018 已提交
359
1.1f 字面量才是 float 类型。
C
CyC2018 已提交
360

C
CyC2018 已提交
361
```java
C
CyC2018 已提交
362
float f = 1.1f;
C
CyC2018 已提交
363 364
```

C
CyC2018 已提交
365 366 367 368 369 370 371 372
## 隐式类型转换

因为字面量 1 是 int 类型,它比 short 类型精度要高,因此不能隐式地将 int 类型下转型为 short 类型。

```java
short s1 = 1;
// s1 = s1 + 1;
```
C
CyC2018 已提交
373

C
CyC2018 已提交
374
但是使用 += 或者 ++ 运算符可以执行隐式类型转换。
C
CyC2018 已提交
375 376 377

```java
s1 += 1;
C
CyC2018 已提交
378
// s1++;
C
CyC2018 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
```

上面的语句相当于将 s1 + 1 的计算结果进行了向下转型:

```java
s1 = (short) (s1 + 1);
```

[StackOverflow : Why don't Java's +=, -=, *=, /= compound assignment operators require casting?](https://stackoverflow.com/questions/8710619/why-dont-javas-compound-assignment-operators-require-casting)

## switch

从 Java 7 开始,可以在 switch 条件判断语句中使用 String 对象。

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

C
CyC2018 已提交
405
switch 不支持 long,是因为 switch 的设计初衷是对那些只有少数的几个值进行等值判断,如果值过于复杂,那么还是用 if 比较合适。
C
CyC2018 已提交
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428

```java
// 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;
// }
```

[StackOverflow : Why can't your switch statement data type be long, Java?](https://stackoverflow.com/questions/2676210/why-cant-your-switch-statement-data-type-be-long-java)

# 四、继承

## 访问权限

Java 中有三个访问权限修饰符:private、protected 以及 public,如果不加访问修饰符,表示包级可见。

可以对类或类中的成员(字段以及方法)加上访问修饰符。

C
CyC2018 已提交
429
- 类可见表示其它类可以用这个类创建实例对象。
C
CyC2018 已提交
430
- 成员可见表示其它类可以用这个类的实例对象访问到该成员;
C
CyC2018 已提交
431 432 433 434 435

protected 用于修饰成员,表示在继承体系中成员对于子类可见,但是这个访问修饰符对于类没有意义。

设计良好的模块会隐藏所有的实现细节,把它的 API 与它的实现清晰地隔离开来。模块之间只通过它们的 API 进行通信,一个模块不需要知道其他模块的内部工作情况,这个概念被称为信息隐藏或封装。因此访问权限应当尽可能地使每个类或者成员不被外界访问。

C
CyC2018 已提交
436
如果子类的方法重写了父类的方法,那么子类中该方法的访问级别不允许低于父类的访问级别。这是为了确保可以使用父类实例的地方都可以使用子类实例,也就是确保满足里氏替换原则。
C
CyC2018 已提交
437

C
CyC2018 已提交
438
字段决不能是公有的,因为这么做的话就失去了对这个字段修改行为的控制,客户端可以对其随意修改。例如下面的例子中,AccessExample 拥有 id 公有字段,如果在某个时刻,我们想要使用 int 存储 id 字段,那么就需要修改所有的客户端代码。
C
CyC2018 已提交
439 440 441

```java
public class AccessExample {
C
CyC2018 已提交
442
    public String id;
C
CyC2018 已提交
443 444 445
}
```

C
CyC2018 已提交
446 447 448
可以使用公有的 getter 和 setter 方法来替换公有字段,这样的话就可以控制对字段的修改行为。


C
CyC2018 已提交
449 450 451
```java
public class AccessExample {

C
CyC2018 已提交
452 453 454 455
    private int id;

    public String getId() {
        return id + "";
C
CyC2018 已提交
456 457
    }

C
CyC2018 已提交
458 459
    public void setId(String id) {
        this.id = Integer.valueOf(id);
C
CyC2018 已提交
460 461 462 463 464 465 466 467
    }
}
```

但是也有例外,如果是包级私有的类或者私有的嵌套类,那么直接暴露成员不会有特别大的影响。

```java
public class AccessWithInnerClassExample {
C
CyC2018 已提交
468

C
CyC2018 已提交
469 470 471 472 473 474 475 476 477 478 479
    private class InnerClass {
        int x;
    }

    private InnerClass innerClass;

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

    public int getValue() {
C
CyC2018 已提交
480
        return innerClass.x;  // 直接访问
C
CyC2018 已提交
481 482 483 484 485 486 487 488
    }
}
```

## 抽象类与接口

**1. 抽象类** 

C
CyC2018 已提交
489
抽象类和抽象方法都使用 abstract 关键字进行声明。抽象类一般会包含抽象方法,抽象方法一定位于抽象类中。
C
CyC2018 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

抽象类和普通类最大的区别是,抽象类不能被实例化,需要继承抽象类才能实例化其子类。

```java
public abstract class AbstractClassExample {

    protected int x;
    private int y;

    public abstract void func1();

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

```java
C
CyC2018 已提交
508
public class AbstractExtendClassExample extends AbstractClassExample {
C
CyC2018 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
    @Override
    public void func1() {
        System.out.println("func1");
    }
}
```

```java
// 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 的。

```java
public interface InterfaceExample {
C
CyC2018 已提交
534

C
CyC2018 已提交
535 536 537 538 539 540 541
    void func1();

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

    int x = 123;
C
CyC2018 已提交
542
    // int y;               // Variable 'y' might not have been initialized
C
CyC2018 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    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
}
```

```java
public class InterfaceImplementExample implements InterfaceExample {
    @Override
    public void func1() {
        System.out.println("func1");
    }
}
```

```java
// 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 类型的,而抽象类的字段没有这种限制。
C
CyC2018 已提交
571
- 接口的成员只能是 public 的,而抽象类的成员可以有多种访问权限。
C
CyC2018 已提交
572 573 574 575 576 577 578 579

**4. 使用选择** 

使用接口:

- 需要让不相关的类都实现一个方法,例如不相关的类都可以实现 Compareable 接口中的 compareTo() 方法;
- 需要使用多重继承。

C
CyC2018 已提交
580 581 582 583 584 585
使用抽象类:

- 需要在几个相关的类中共享代码。
- 需要能控制继承来的成员的访问权限,而不是都为 public。
- 需要继承非静态和非常量字段。

C
CyC2018 已提交
586
在很多情况下,接口优先于抽象类。因为接口没有抽象类严格的类层次结构要求,可以灵活地为一个类添加行为。并且从 Java 8 开始,接口也可以有默认的方法实现,使得修改接口的成本也变的很低。
C
CyC2018 已提交
587

C
CyC2018 已提交
588 589
- [深入理解 abstract class 和 interface](https://www.ibm.com/developerworks/cn/java/l-javainterface-abstract/)
- [When to Use Abstract Class and Interface](https://dzone.com/articles/when-to-use-abstract-class-and-intreface)
C
CyC2018 已提交
590 591 592

## super

C
CyC2018 已提交
593
- 访问父类的构造函数:可以使用 super() 函数访问父类的构造函数,从而委托父类完成一些初始化的工作。
C
CyC2018 已提交
594
- 访问父类的成员:如果子类重写了父类的某个方法,可以通过使用 super 关键字来引用父类的方法实现。
C
CyC2018 已提交
595 596 597

```java
public class SuperExample {
C
CyC2018 已提交
598

C
CyC2018 已提交
599 600
    protected int x;
    protected int y;
C
CyC2018 已提交
601

C
CyC2018 已提交
602 603 604 605
    public SuperExample(int x, int y) {
        this.x = x;
        this.y = y;
    }
C
CyC2018 已提交
606

C
CyC2018 已提交
607 608 609 610
    public void func() {
        System.out.println("SuperExample.func()");
    }
}
C
CyC2018 已提交
611 612 613
```

```java
C
CyC2018 已提交
614
public class SuperExtendExample extends SuperExample {
C
CyC2018 已提交
615

C
CyC2018 已提交
616 617 618 619 620 621 622 623 624 625 626 627
    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()");
    }
C
CyC2018 已提交
628 629 630 631
}
```

```java
C
CyC2018 已提交
632 633
SuperExample e = new SuperExtendExample(1, 2, 3);
e.func();
C
CyC2018 已提交
634 635
```

C
CyC2018 已提交
636 637 638
```html
SuperExample.func()
SuperExtendExample.func()
C
CyC2018 已提交
639 640
```

C
CyC2018 已提交
641
[Using the Keyword super](https://docs.oracle.com/javase/tutorial/java/IandI/super.html)
C
CyC2018 已提交
642

C
CyC2018 已提交
643
## 重写与重载
C
CyC2018 已提交
644

C
CyC2018 已提交
645
**1. 重写(Override)** 
C
CyC2018 已提交
646

C
CyC2018 已提交
647 648 649 650 651 652 653 654 655 656 657 658 659 660
存在于继承体系中,指子类实现了一个与父类在方法声明上完全相同的一个方法。

为了满足里式替换原则,重写有有以下两个限制:

- 子类方法的访问权限必须大于等于父类方法;
- 子类方法的返回类型必须是父类方法返回类型或为其子类型。

使用 @Override 注解,可以让编译器帮忙检查是否满足上面的两个限制条件。

**2. 重载(Overload)** 

存在于同一个类中,指一个方法与已经存在的方法名称上相同,但是参数类型、个数、顺序至少有一个不同。

应该注意的是,返回值不同,其它都相同不算是重载。
C
CyC2018 已提交
661

C
CyC2018 已提交
662
# 五、Object 通用方法
C
CyC2018 已提交
663

C
CyC2018 已提交
664
## 概览
C
CyC2018 已提交
665 666 667

```java

C
CyC2018 已提交
668
public native int hashCode()
C
CyC2018 已提交
669

C
CyC2018 已提交
670
public boolean equals(Object obj)
C
CyC2018 已提交
671

C
CyC2018 已提交
672
protected native Object clone() throws CloneNotSupportedException
C
CyC2018 已提交
673

C
CyC2018 已提交
674
public String toString()
C
CyC2018 已提交
675

C
CyC2018 已提交
676 677 678 679
public final native Class<?> getClass()

protected void finalize() throws Throwable {}

C
CyC2018 已提交
680
public final native void notify()
C
CyC2018 已提交
681

C
CyC2018 已提交
682
public final native void notifyAll()
C
CyC2018 已提交
683

C
CyC2018 已提交
684
public final native void wait(long timeout) throws InterruptedException
C
CyC2018 已提交
685

C
CyC2018 已提交
686
public final void wait(long timeout, int nanos) throws InterruptedException
C
CyC2018 已提交
687

C
CyC2018 已提交
688
public final void wait() throws InterruptedException
C
CyC2018 已提交
689 690
```

C
CyC2018 已提交
691
## equals()
C
CyC2018 已提交
692

C
CyC2018 已提交
693
**1. 等价关系** 
C
CyC2018 已提交
694

C
CyC2018 已提交
695
Ⅰ 自反性
C
CyC2018 已提交
696 697

```java
C
CyC2018 已提交
698
x.equals(x); // true
C
CyC2018 已提交
699 700
```

C
CyC2018 已提交
701
Ⅱ 对称性
C
CyC2018 已提交
702 703

```java
C
CyC2018 已提交
704
x.equals(y) == y.equals(x); // true
C
CyC2018 已提交
705 706
```

C
CyC2018 已提交
707
Ⅲ 传递性
C
CyC2018 已提交
708 709

```java
C
CyC2018 已提交
710 711
if (x.equals(y) && y.equals(z))
    x.equals(z); // true;
C
CyC2018 已提交
712 713
```

C
CyC2018 已提交
714
Ⅳ 一致性
C
CyC2018 已提交
715

C
CyC2018 已提交
716
多次调用 equals() 方法结果不变
C
CyC2018 已提交
717 718

```java
C
CyC2018 已提交
719
x.equals(y) == x.equals(y); // true
C
CyC2018 已提交
720 721
```

C
CyC2018 已提交
722
Ⅴ 与 null 的比较
C
CyC2018 已提交
723

C
CyC2018 已提交
724
对任何不是 null 的对象 x 调用 x.equals(null) 结果都为 false
C
CyC2018 已提交
725 726

```java
C
CyC2018 已提交
727
x.equals(null); // false;
C
CyC2018 已提交
728 729
```

C
CyC2018 已提交
730
**2. 等价与相等** 
C
CyC2018 已提交
731 732

- 对于基本类型,== 判断两个值是否相等,基本类型没有 equals() 方法。
C
CyC2018 已提交
733
- 对于引用类型,== 判断两个变量是否引用同一个对象,而 equals() 判断引用的对象是否等价。
C
CyC2018 已提交
734 735 736 737 738 739 740 741

```java
Integer x = new Integer(1);
Integer y = new Integer(1);
System.out.println(x.equals(y)); // true
System.out.println(x == y);      // false
```

C
CyC2018 已提交
742
**3. 实现** 
C
CyC2018 已提交
743

C
CyC2018 已提交
744 745
- 检查是否为同一个对象的引用,如果是直接返回 true;
- 检查是否是同一个类型,如果不是,直接返回 false;
C
CyC2018 已提交
746
- 将 Object 对象进行转型;
C
CyC2018 已提交
747
- 判断每个关键域是否相等。
C
CyC2018 已提交
748 749

```java
C
CyC2018 已提交
750
public class EqualExample {
C
CyC2018 已提交
751

C
CyC2018 已提交
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
    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;
    }
C
CyC2018 已提交
773 774 775
}
```

C
CyC2018 已提交
776
## hashCode()
C
CyC2018 已提交
777

C
CyC2018 已提交
778
hashCode() 返回散列值,而 equals() 是用来判断两个对象是否等价。等价的两个对象散列值一定相同,但是散列值相同的两个对象不一定等价。
C
CyC2018 已提交
779

C
CyC2018 已提交
780
在覆盖 equals() 方法时应当总是覆盖 hashCode() 方法,保证等价的两个对象散列值也相等。
C
CyC2018 已提交
781

C
CyC2018 已提交
782
下面的代码中,新建了两个等价的对象,并将它们添加到 HashSet 中。我们希望将这两个对象当成一样的,只在集合中添加一个对象,但是因为 EqualExample 没有实现 hasCode() 方法,因此这两个对象的散列值是不同的,最终导致集合添加了两个等价的对象。
C
CyC2018 已提交
783 784

```java
C
CyC2018 已提交
785 786 787 788
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<>();
C
CyC2018 已提交
789 790
set.add(e1);
set.add(e2);
C
CyC2018 已提交
791
System.out.println(set.size());   // 2
C
CyC2018 已提交
792 793
```

C
CyC2018 已提交
794
理想的散列函数应当具有均匀性,即不相等的对象应当均匀分布到所有可能的散列值上。这就要求了散列函数要把所有域的值都考虑进来。可以将每个域都当成 R 进制的某一位,然后组成一个 R 进制的整数。R 一般取 31,因为它是一个奇素数,如果是偶数的话,当出现乘法溢出,信息就会丢失,因为与 2 相乘相当于向左移一位。
C
CyC2018 已提交
795

C
CyC2018 已提交
796
一个数与 31 相乘可以转换成移位和减法:`31*x == (x<<5)-x`,编译器会自动进行这个优化。
C
CyC2018 已提交
797 798 799

```java
@Override
C
CyC2018 已提交
800 801 802 803 804 805
public int hashCode() {
    int result = 17;
    result = 31 * result + x;
    result = 31 * result + y;
    result = 31 * result + z;
    return result;
C
CyC2018 已提交
806 807 808
}
```

C
CyC2018 已提交
809
## toString()
C
CyC2018 已提交
810

C
CyC2018 已提交
811
默认返回 ToStringExample@4554617c 这种形式,其中 @ 后面的数值为散列码的无符号十六进制表示。
C
CyC2018 已提交
812 813

```java
C
CyC2018 已提交
814
public class ToStringExample {
C
CyC2018 已提交
815

C
CyC2018 已提交
816
    private int number;
C
CyC2018 已提交
817

C
CyC2018 已提交
818 819 820
    public ToStringExample(int number) {
        this.number = number;
    }
C
CyC2018 已提交
821 822 823 824
}
```

```java
C
CyC2018 已提交
825
ToStringExample example = new ToStringExample(123);
C
CyC2018 已提交
826 827 828 829 830 831 832
System.out.println(example.toString());
```

```html
ToStringExample@4554617c
```

C
CyC2018 已提交
833
## clone()
C
CyC2018 已提交
834

C
CyC2018 已提交
835
**1. cloneable** 
C
CyC2018 已提交
836

C
CyC2018 已提交
837
clone() 是 Object 的 protected 方法,它不是 public,一个类不显式去重写 clone(),其它类就不能直接去调用该类实例的 clone() 方法。
C
CyC2018 已提交
838 839

```java
C
CyC2018 已提交
840 841 842
public class CloneExample {
    private int a;
    private int b;
C
CyC2018 已提交
843 844 845 846
}
```

```java
C
CyC2018 已提交
847 848
CloneExample e1 = new CloneExample();
// CloneExample e2 = e1.clone(); // 'clone()' has protected access in 'java.lang.Object'
C
CyC2018 已提交
849 850
```

C
CyC2018 已提交
851
重写 clone() 得到以下实现:
C
CyC2018 已提交
852 853

```java
C
CyC2018 已提交
854 855 856 857 858
public class CloneExample {
    private int a;
    private int b;

    @Override
C
CyC2018 已提交
859
    public CloneExample clone() throws CloneNotSupportedException {
C
CyC2018 已提交
860 861
        return (CloneExample)super.clone();
    }
C
CyC2018 已提交
862 863 864 865
}
```

```java
C
CyC2018 已提交
866 867 868 869 870
CloneExample e1 = new CloneExample();
try {
    CloneExample e2 = e1.clone();
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
C
CyC2018 已提交
871 872 873 874
}
```

```html
C
CyC2018 已提交
875
java.lang.CloneNotSupportedException: CloneExample
C
CyC2018 已提交
876 877
```

C
CyC2018 已提交
878
以上抛出了 CloneNotSupportedException,这是因为 CloneExample 没有实现 Cloneable 接口。
C
CyC2018 已提交
879

C
CyC2018 已提交
880 881
应该注意的是,clone() 方法并不是 Cloneable 接口的方法,而是 Object 的一个 protected 方法。Cloneable 接口只是规定,如果一个类没有实现 Cloneable 接口又调用了 clone() 方法,就会抛出 CloneNotSupportedException。

C
CyC2018 已提交
882
```java
C
CyC2018 已提交
883 884 885 886 887
public class CloneExample implements Cloneable {
    private int a;
    private int b;

    @Override
C
CyC2018 已提交
888
    public Object clone() throws CloneNotSupportedException {
C
CyC2018 已提交
889 890
        return super.clone();
    }
C
CyC2018 已提交
891 892 893
}
```

C
CyC2018 已提交
894
**2. 浅拷贝** 
C
CyC2018 已提交
895

C
CyC2018 已提交
896
拷贝对象和原始对象的引用类型引用同一个对象。
C
CyC2018 已提交
897 898

```java
C
CyC2018 已提交
899
public class ShallowCloneExample implements Cloneable {
C
CyC2018 已提交
900

C
CyC2018 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
    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();
    }
C
CyC2018 已提交
922 923 924 925
}
```

```java
C
CyC2018 已提交
926 927 928 929 930 931
ShallowCloneExample e1 = new ShallowCloneExample();
ShallowCloneExample e2 = null;
try {
    e2 = e1.clone();
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
C
CyC2018 已提交
932
}
C
CyC2018 已提交
933 934
e1.set(2, 222);
System.out.println(e2.get(2)); // 222
C
CyC2018 已提交
935 936
```

C
CyC2018 已提交
937 938 939 940
**3. 深拷贝** 

拷贝对象和原始对象的引用类型引用不同对象。

C
CyC2018 已提交
941
```java
C
CyC2018 已提交
942
public class DeepCloneExample implements Cloneable {
C
CyC2018 已提交
943

C
CyC2018 已提交
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
    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;
    }
C
CyC2018 已提交
970 971 972 973
}
```

```java
C
CyC2018 已提交
974 975 976 977 978 979 980 981
DeepCloneExample e1 = new DeepCloneExample();
DeepCloneExample e2 = null;
try {
    e2 = e1.clone();
} catch (CloneNotSupportedException e) {
    e.printStackTrace();
}
e1.set(2, 222);
C
CyC2018 已提交
982 983
System.out.println(e2.get(2)); // 2
```
C
CyC2018 已提交
984

C
CyC2018 已提交
985 986
**4. clone() 的替代方案** 

C
CyC2018 已提交
987
使用 clone() 方法来拷贝一个对象即复杂又有风险,它会抛出异常,并且还需要类型转换。Effective Java 书上讲到,最好不要去使用 clone(),可以使用拷贝构造函数或者拷贝工厂来拷贝一个对象。
C
CyC2018 已提交
988 989

```java
C
CyC2018 已提交
990
public class CloneConstructorExample {
C
CyC2018 已提交
991

C
CyC2018 已提交
992
    private int[] arr;
C
CyC2018 已提交
993

C
CyC2018 已提交
994 995 996 997 998
    public CloneConstructorExample() {
        arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i;
        }
C
CyC2018 已提交
999 1000
    }

C
CyC2018 已提交
1001 1002 1003 1004 1005
    public CloneConstructorExample(CloneConstructorExample original) {
        arr = new int[original.arr.length];
        for (int i = 0; i < original.arr.length; i++) {
            arr[i] = original.arr[i];
        }
C
CyC2018 已提交
1006 1007
    }

C
CyC2018 已提交
1008 1009
    public void set(int index, int value) {
        arr[index] = value;
C
CyC2018 已提交
1010 1011
    }

C
CyC2018 已提交
1012 1013
    public int get(int index) {
        return arr[index];
C
CyC2018 已提交
1014
    }
C
CyC2018 已提交
1015 1016 1017 1018
}
```

```java
C
CyC2018 已提交
1019 1020 1021 1022
CloneConstructorExample e1 = new CloneConstructorExample();
CloneConstructorExample e2 = new CloneConstructorExample(e1);
e1.set(2, 222);
System.out.println(e2.get(2)); // 2
C
CyC2018 已提交
1023 1024
```

C
CyC2018 已提交
1025
# 六、关键字
C
CyC2018 已提交
1026

C
CyC2018 已提交
1027
## final
C
CyC2018 已提交
1028

C
CyC2018 已提交
1029
**1. 数据** 
C
CyC2018 已提交
1030

C
CyC2018 已提交
1031
声明数据为常量,可以是编译时常量,也可以是在运行时被初始化后不能被改变的常量。
C
CyC2018 已提交
1032

C
CyC2018 已提交
1033 1034
- 对于基本类型,final 使数值不变;
- 对于引用类型,final 使引用不变,也就不能引用其它对象,但是被引用的对象本身是可以修改的。
C
CyC2018 已提交
1035

C
CyC2018 已提交
1036 1037 1038 1039 1040 1041
```java
final int x = 1;
// x = 2;  // cannot assign value to final variable 'x'
final A y = new A();
y.a = 1;
```
C
CyC2018 已提交
1042

C
CyC2018 已提交
1043
**2. 方法** 
C
CyC2018 已提交
1044

C
CyC2018 已提交
1045
声明方法不能被子类重写。
C
CyC2018 已提交
1046

C
CyC2018 已提交
1047
private 方法隐式地被指定为 final,如果在子类中定义的方法和基类中的一个 private 方法签名相同,此时子类的方法不是重写基类方法,而是在子类中定义了一个新的方法。
C
CyC2018 已提交
1048

C
CyC2018 已提交
1049
**3. 类** 
C
CyC2018 已提交
1050

C
CyC2018 已提交
1051
声明类不允许被继承。
C
CyC2018 已提交
1052

C
CyC2018 已提交
1053
## static
C
CyC2018 已提交
1054

C
CyC2018 已提交
1055
**1. 静态变量** 
C
CyC2018 已提交
1056

C
CyC2018 已提交
1057
- 静态变量:又称为类变量,也就是说这个变量属于类的,类所有的实例都共享静态变量,可以直接通过类名来访问它。静态变量在内存中只存在一份。
C
CyC2018 已提交
1058
- 实例变量:每创建一个实例就会产生一个实例变量,它与该实例同生共死。
C
CyC2018 已提交
1059

C
CyC2018 已提交
1060 1061
```java
public class A {
C
CyC2018 已提交
1062

C
CyC2018 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    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;
    }
}
```
C
CyC2018 已提交
1074

C
CyC2018 已提交
1075
**2. 静态方法** 
C
CyC2018 已提交
1076

C
CyC2018 已提交
1077
静态方法在类加载的时候就存在了,它不依赖于任何实例。所以静态方法必须有实现,也就是说它不能是抽象方法。
C
CyC2018 已提交
1078

C
CyC2018 已提交
1079 1080 1081 1082 1083 1084 1085
```java
public abstract class A {
    public static void func1(){
    }
    // public abstract static void func2();  // Illegal combination of modifiers: 'abstract' and 'static'
}
```
C
CyC2018 已提交
1086

C
CyC2018 已提交
1087
只能访问所属类的静态字段和静态方法,方法中不能有 this 和 super 关键字。
C
CyC2018 已提交
1088

C
CyC2018 已提交
1089 1090
```java
public class A {
C
CyC2018 已提交
1091

C
CyC2018 已提交
1092 1093
    private static int x;
    private int y;
C
CyC2018 已提交
1094

C
CyC2018 已提交
1095 1096 1097 1098 1099 1100 1101
    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
    }
}
```
C
CyC2018 已提交
1102

C
CyC2018 已提交
1103
**3. 静态语句块** 
C
CyC2018 已提交
1104

C
CyC2018 已提交
1105
静态语句块在类初始化时运行一次。
C
CyC2018 已提交
1106

C
CyC2018 已提交
1107 1108 1109 1110 1111
```java
public class A {
    static {
        System.out.println("123");
    }
C
CyC2018 已提交
1112

C
CyC2018 已提交
1113 1114 1115 1116 1117
    public static void main(String[] args) {
        A a1 = new A();
        A a2 = new A();
    }
}
C
CyC2018 已提交
1118 1119
```

C
CyC2018 已提交
1120 1121
```html
123
C
CyC2018 已提交
1122 1123
```

C
CyC2018 已提交
1124
**4. 静态内部类** 
C
CyC2018 已提交
1125

C
CyC2018 已提交
1126
非静态内部类依赖于外部类的实例,而静态内部类不需要。
C
CyC2018 已提交
1127

C
CyC2018 已提交
1128 1129
```java
public class OuterClass {
C
CyC2018 已提交
1130

C
CyC2018 已提交
1131 1132
    class InnerClass {
    }
C
CyC2018 已提交
1133

C
CyC2018 已提交
1134 1135
    static class StaticInnerClass {
    }
C
CyC2018 已提交
1136

C
CyC2018 已提交
1137 1138 1139 1140 1141 1142 1143 1144
    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();
    }
}
```
C
CyC2018 已提交
1145

C
CyC2018 已提交
1146
静态内部类不能访问外部类的非静态的变量和方法。
C
CyC2018 已提交
1147

C
CyC2018 已提交
1148
**5. 静态导包** 
C
CyC2018 已提交
1149

C
CyC2018 已提交
1150 1151
在使用静态变量和方法时不用再指明 ClassName,从而简化代码,但可读性大大降低。

C
CyC2018 已提交
1152
```java
C
CyC2018 已提交
1153
import static com.xxx.ClassName.*
C
CyC2018 已提交
1154 1155
```

C
CyC2018 已提交
1156
**6. 初始化顺序** 
C
CyC2018 已提交
1157

C
CyC2018 已提交
1158
静态变量和静态语句块优先于实例变量和普通语句块,静态变量和静态语句块的初始化顺序取决于它们在代码中的顺序。
C
CyC2018 已提交
1159 1160

```java
C
CyC2018 已提交
1161
public static String staticField = "静态变量";
C
CyC2018 已提交
1162 1163 1164
```

```java
C
CyC2018 已提交
1165 1166
static {
    System.out.println("静态语句块");
C
CyC2018 已提交
1167 1168 1169
}
```

C
CyC2018 已提交
1170
```java
C
CyC2018 已提交
1171
public String field = "实例变量";
C
CyC2018 已提交
1172 1173
```

C
CyC2018 已提交
1174
```java
C
CyC2018 已提交
1175 1176
{
    System.out.println("普通语句块");
C
CyC2018 已提交
1177 1178
}
```
C
CyC2018 已提交
1179

C
CyC2018 已提交
1180
最后才是构造函数的初始化。
C
CyC2018 已提交
1181 1182

```java
C
CyC2018 已提交
1183 1184 1185
public InitialOrderTest() {
    System.out.println("构造函数");
}
C
CyC2018 已提交
1186 1187
```

C
CyC2018 已提交
1188 1189 1190 1191 1192 1193 1194 1195
存在继承的情况下,初始化顺序为:

- 父类(静态变量、静态语句块)
- 子类(静态变量、静态语句块)
- 父类(实例变量、普通语句块)
- 父类(构造函数)
- 子类(实例变量、普通语句块)
- 子类(构造函数)
C
CyC2018 已提交
1196

C
CyC2018 已提交
1197

C
CyC2018 已提交
1198
# 七、反射
C
CyC2018 已提交
1199

C
CyC2018 已提交
1200
每个类都有一个  **Class**  对象,包含了与类有关的信息。当编译一个新类时,会产生一个同名的 .class 文件,该文件内容保存着 Class 对象。
C
CyC2018 已提交
1201

C
CyC2018 已提交
1202
类加载相当于 Class 对象的加载,类在第一次使用时才动态加载到 JVM 中。也可以使用 `Class.forName("com.mysql.jdbc.Driver")` 这种方式来控制类的加载,该方法会返回一个 Class 对象。
C
CyC2018 已提交
1203

C
CyC2018 已提交
1204
反射可以提供运行时的类信息,并且这个类可以在运行时才加载进来,甚至在编译时期该类的 .class 不存在也可以加载进来。
C
CyC2018 已提交
1205

C
CyC2018 已提交
1206
Class 和 java.lang.reflect 一起对反射提供了支持,java.lang.reflect 类库主要包含了以下三个类:
C
CyC2018 已提交
1207

C
CyC2018 已提交
1208 1209 1210
-  **Field** :可以使用 get() 和 set() 方法读取和修改 Field 对象关联的字段;
-  **Method** :可以使用 invoke() 方法调用与 Method 对象关联的方法;
-  **Constructor** :可以用 Constructor 创建新的对象。
C
CyC2018 已提交
1211

C
CyC2018 已提交
1212
**反射的优点:** 
C
CyC2018 已提交
1213

C
CyC2018 已提交
1214 1215 1216
*    **可扩展性**  :应用程序可以利用全限定名创建可扩展对象的实例,来使用来自外部的用户自定义类。
*    **类浏览器和可视化开发环境**  :一个类浏览器需要可以枚举类的成员。可视化开发环境(如 IDE)可以从利用反射中可用的类型信息中受益,以帮助程序员编写正确的代码。
*    **调试器和测试工具**  : 调试器需要能够检查一个类里的私有成员。测试工具可以利用反射来自动地调用类里定义的可被发现的 API 定义,以确保一组测试中有较高的代码覆盖率。
C
CyC2018 已提交
1217

C
CyC2018 已提交
1218
**反射的缺点:** 
C
CyC2018 已提交
1219

Q
q147258134 已提交
1220
尽管反射非常强大,但也不能滥用。如果一个功能可以不用反射完成,那么最好就不用。在我们使用反射技术时,下面几条内容应该牢记于心。
C
CyC2018 已提交
1221

C
CyC2018 已提交
1222 1223 1224 1225 1226
*    **性能开销**  :反射涉及了动态类型的解析,所以 JVM 无法对这些代码进行优化。因此,反射操作的效率要比那些非反射操作低得多。我们应该避免在经常被执行的代码或对性能要求很高的程序中使用反射。

*    **安全限制**  :使用反射技术要求程序必须在一个没有安全限制的环境中运行。如果一个程序必须在有安全限制的环境中运行,如 Applet,那么这就是个问题了。

*    **内部暴露**  :由于反射允许代码执行一些在正常情况下不被允许的操作(比如访问私有的属性和方法),所以使用反射可能会导致意料之外的副作用,这可能导致代码功能失调并破坏可移植性。反射代码破坏了抽象性,因此当平台发生改变的时候,代码的行为就有可能也随着变化。
C
CyC2018 已提交
1227

C
CyC2018 已提交
1228 1229 1230

- [Trail: The Reflection API](https://docs.oracle.com/javase/tutorial/reflect/index.html)
- [深入解析 Java 反射(1)- 基础](http://www.sczyh30.com/posts/Java/java-reflection-1/)
C
CyC2018 已提交
1231

C
CyC2018 已提交
1232
# 八、异常
C
CyC2018 已提交
1233

C
CyC2018 已提交
1234
Throwable 可以用来表示任何可以作为异常抛出的类,分为两种: **Error****Exception**。其中 Error 用来表示 JVM 无法处理的错误,Exception 分为两种:
C
CyC2018 已提交
1235

C
CyC2018 已提交
1236
-  **受检异常** :需要用 try...catch... 语句捕获并进行处理,并且可以从异常中恢复;
C
CyC2018 已提交
1237
-  **非受检异常** :是程序运行时错误,例如除 0 会引发 Arithmetic Exception,此时程序崩溃并且无法恢复。
C
CyC2018 已提交
1238

C
fix  
CyC2018 已提交
1239
<div align="center"> <img src="pics/PPjwP.png" width="600"/> </div><br>
C
CyC2018 已提交
1240

C
CyC2018 已提交
1241 1242
- [Java 入门之异常处理](https://www.tianmaying.com/tutorial/Java-Exception)
- [Java 异常的面试问题及答案 -Part 1](http://www.importnew.com/7383.html)
C
CyC2018 已提交
1243

C
CyC2018 已提交
1244
# 九、泛型
C
CyC2018 已提交
1245 1246

```java
C
CyC2018 已提交
1247 1248 1249 1250 1251
public class Box<T> {
    // T stands for "Type"
    private T t;
    public void set(T t) { this.t = t; }
    public T get() { return t; }
C
CyC2018 已提交
1252 1253 1254
}
```

C
CyC2018 已提交
1255 1256
- [Java 泛型详解](http://www.importnew.com/24029.html)
- [10 道 Java 泛型面试题](https://cloud.tencent.com/developer/article/1033693)
C
CyC2018 已提交
1257

C
CyC2018 已提交
1258
# 十、注解
C
CyC2018 已提交
1259

C
CyC2018 已提交
1260
Java 注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。
C
CyC2018 已提交
1261

C
CyC2018 已提交
1262
[注解 Annotation 实现原理与自定义注解例子](https://www.cnblogs.com/acm-bingzi/p/javaAnnotation.html)
C
CyC2018 已提交
1263

C
CyC2018 已提交
1264
# 十一、特性
C
CyC2018 已提交
1265

C
CyC2018 已提交
1266
## Java 各版本的新特性
C
CyC2018 已提交
1267

C
CyC2018 已提交
1268
**New highlights in Java SE 8** 
C
CyC2018 已提交
1269

C
CyC2018 已提交
1270 1271 1272 1273 1274 1275 1276 1277 1278
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
C
CyC2018 已提交
1279

C
CyC2018 已提交
1280
**New highlights in Java SE 7** 
C
CyC2018 已提交
1281

C
CyC2018 已提交
1282 1283 1284 1285 1286 1287 1288 1289
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
C
CyC2018 已提交
1290

C
CyC2018 已提交
1291 1292
- [Difference between Java 1.8 and Java 1.7?](http://www.selfgrowth.com/articles/difference-between-java-18-and-java-17)
- [Java 8 特性](http://www.importnew.com/19345.html)
C
CyC2018 已提交
1293

C
CyC2018 已提交
1294
## Java 与 C++ 的区别
C
CyC2018 已提交
1295

C
CyC2018 已提交
1296 1297 1298 1299 1300
- Java 是纯粹的面向对象语言,所有的对象都继承自 java.lang.Object,C++ 为了兼容 C 即支持面向对象也支持面向过程。
- Java 通过虚拟机从而实现跨平台特性,但是 C++ 依赖于特定的平台。
- Java 没有指针,它的引用可以理解为安全指针,而 C++ 具有和 C 一样的指针。
- Java 支持自动垃圾回收,而 C++ 需要手动回收。
- Java 不支持多重继承,只能通过实现多个接口来达到相同目的,而 C++ 支持多重继承。
C
CyC2018 已提交
1301
- Java 不支持操作符重载,虽然可以对两个 String 对象执行加法运算,但是这是语言内置支持的操作,不属于操作符重载,而 C++ 可以。
C
CyC2018 已提交
1302 1303
- Java 的 goto 是保留字,但是不可用,C++ 可以使用 goto。
- Java 不支持条件编译,C++ 通过 #ifdef #ifndef 等预处理命令从而实现条件编译。
C
CyC2018 已提交
1304

C
CyC2018 已提交
1305
[What are the main differences between Java and C++?](http://cs-fundamentals.com/tech-interview/java/differences-between-java-and-cpp.php)
C
CyC2018 已提交
1306

C
CyC2018 已提交
1307
## JRE or JDK
C
CyC2018 已提交
1308

C
CyC2018 已提交
1309 1310
- 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"
C
CyC2018 已提交
1311

C
CyC2018 已提交
1312
# 参考资料
C
CyC2018 已提交
1313

C
CyC2018 已提交
1314 1315
- Eckel B. Java 编程思想[M]. 机械工业出版社, 2002.
- Bloch J. Effective java[M]. Addison-Wesley Professional, 2017.