1. “is-a” and “has-a” relationships
在Java中,“is-a” 代表的是類之間的繼承關系,比如我們之前建立的Circle和Geometry兩個類,我們就可以說“a Circle is-a Geometry”,也就是說:Circle是Geometry的子類,或者,Geometry是Circle的父類。
“has-a”關系,代表的是一種從屬關系。比如,我們建立一個類叫Student,并在Student里定義一個Integer型的實例變量studentID;我們就可以說“a Student has an Integer studentID,” 即“每個學生都有一個學號”。這里的Student和Integer之間就是has-a的關系。
2. null
我們都知道,引用類型變量存儲的值是對象的地址。如果我們聲明了一個引用類型變量,而沒有給其賦值,那么,這個引用類型變量的值就是null,或者說:“the reference variable has a null reference.”
有時候,我們想要清除一個引用類型變量的值,也可以將null賦值給這個變量。一般來說,如果一個變量的值是null,那么就不可以使用這個變量去調用方法。
值得注意的是:null和empty是兩個不同的概念。比如我們可以創建兩個String型變量:
String str1 = null;
String str2 = "";
str1的引用就是null,即str1不指向任何一個字符串;而str2的引用就不是null,str2指向了一個字符串,只不過這個字符串是空的(empty),里面什么字符都沒有。
3. this
關鍵詞this可以用來引用當前對象,或者說: “the keyword this is a reference to the object whose method or constructor is being called.”我們還可以稱之為隱式參數(the implicit parameter)。比如下面這個例子:
public static void main(String[] args)
{
TheClass myObject = new TheClass();
myObject.doSomething();
}
public class TheClass
{
public void doSomething()
{
doSomethingElse(this);
}
public void doSomethingElse(TheClass object)
{
System.out.println("This is an example.");
}
}
顯示結果就是:
This is an example.
4. super.method(args)
之前我們提到過,子類中可以調用父類的方法。如果我們已經在子類中重寫了一個父類中的方法,但是仍然想要在子類中使用父類的這個方法的時候,我們就可以使用super.method(args)來調用這個在父類中的方法,比如:
public class Circle extends Geometry
{
private double radius;
public String getColor()
{
return "Color has been changed from " + super.getColor() + " to Black.";
}
}
public class Geometry
{
private String color = "White";
public String getColor()
{
return color;
}
}
下面,給大家留一道小題:
public class Father
{
public void doSomething(Father object)
{
System.out.println("Father");
}
}
public class Son extends Father
{
public void doSomethingElse()
{
super.doSomething(this);
}
public void doSomething(Father object)
{
System.out.println("Son");
}
}
如上,我們建立了一個父類和一個子類,請問下面代碼運行之后的輸出結果是什么?
Son object = new Son();
object.doSomethingElse();
附:AP CS A Free Response Questions?下載地址:
https://apcentral.collegeboard.org/courses/ap-computer-science-a/exam

? 2025. All Rights Reserved. 滬ICP備2023009024號-1