mirror of
https://gitee.com/gaohongy/Java-Book.git
synced 2026-07-16 10:33:49 +00:00
修复图片
This commit is contained in:
+1
-1
@@ -140,7 +140,7 @@ Character类的`Character.isDigit(char)`,`Character.isLetter(char)`这些函
|
|||||||
|
|
||||||
#### 2.1.3. 数值类封装类型的常量
|
#### 2.1.3. 数值类封装类型的常量
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
例如Integer和Double(其他数值类一样),都有MAX_VALUE和MIN_VALUE两个常量,且是静态的。
|
例如Integer和Double(其他数值类一样),都有MAX_VALUE和MIN_VALUE两个常量,且是静态的。
|
||||||
|
|
||||||
|
|||||||
+20
-23
@@ -547,14 +547,11 @@ classDiagram
|
|||||||
}
|
}
|
||||||
class Orange{
|
class Orange{
|
||||||
+toString()
|
+toString()
|
||||||
|
+printInfo()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
有三个类
|
有三个类:Fruit是父类,Apple和Orange都从Fruit扩展而来,且都覆盖了其toString()方法。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
```Java
|
```Java
|
||||||
class Fruit {
|
class Fruit {
|
||||||
@@ -573,6 +570,10 @@ class Orange extends Fruit {
|
|||||||
public String toString() {
|
public String toString() {
|
||||||
return "This is an orange.";
|
return "This is an orange.";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void printInfo() {
|
||||||
|
System.out.println("My name is Orange.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class Test {
|
public class Test {
|
||||||
@@ -585,6 +586,20 @@ public class Test {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
注意分析主函数中的 `Fruit fruit = new Apple();`这一行代码。变量类型是Fruit,而实际的对象是Apple(注意:Apple是Fruit的子类)。这样类型都不一样,可以赋值吗?这样做是完全合法的,多态的一个重要用法是用父类的引用变量类引用(指向)子类的对象。
|
||||||
|
|
||||||
|
这样理解可能会好一些:
|
||||||
|
|
||||||
|
1. 变量类型声明是**调用能力声明**;
|
||||||
|
2. 对一个对象的能力声明并不一定是该对象的全部能力;
|
||||||
|
3. 子类型对象的能力一定不小于父类型对象的能力;
|
||||||
|
|
||||||
|
上面例子中真实的对象是Apple,能力声明是Fruit。因为Apple的能力不小于Fruit,因此我用Fruit类型声明的变量去调用Apple的对象不存在任何问题。但 是因为能力声明的限制,只能调用Fruit这个类型所具备的能力(例如,Orange类型有一个printInfo()函数,就无法在 Fruit的引用变量上调用)。
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
上面的例子有些抽象,我们举一个生活中具体的例子:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### 5.2. 复杂一点的例子
|
### 5.2. 复杂一点的例子
|
||||||
@@ -592,24 +607,6 @@ public class Test {
|
|||||||
我们先来看看一个例子:
|
我们先来看看一个例子:
|
||||||
|
|
||||||
```java
|
```java
|
||||||
class Fruit {
|
|
||||||
public String toString() {
|
|
||||||
return "This is fruit.";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Apple extends Fruit {
|
|
||||||
public String toString() {
|
|
||||||
return "This is an apple.";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Orange extends Fruit {
|
|
||||||
public String toString() {
|
|
||||||
return "This is an orange.";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Test {
|
public class Test {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
Apple apple = new Apple();
|
Apple apple = new Apple();
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
Reference in New Issue
Block a user