在他的"Thinking In Java,4th Ed."中的第428页(关于类型信息的章节)中,Bruce Eckel有以下示例:
public class Staff extends ArrayList<Position> {
public void add(String title, Person person) {
add(new Position(title, person));
}
/* rest of code snipped */
Run Code Online (Sandbox Code Playgroud)
也许我有点累,但我看不出add()方法中add()的调用是如何工作的.我一直认为它应该有一个引用,或者是一个静态方法(我在ArrayList或List中找不到静态add()).我错过了什么?
我刚刚为自己测试过,发现这个有效:
// Test2.java
public class Test2 {
public void testMethod() {
testMethod2();
}
public void testMethod2() {
System.out.println("Here");
}
public static void main(String[] args) {
Test2 t = new Test2();
t.testMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
Daf*_*aff 43
Java隐式地假定对这样调用的方法的当前对象的引用.所以
// Test2.java
public class Test2 {
public void testMethod() {
testMethod2();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
完全一样
// Test2.java
public class Test2 {
public void testMethod() {
this.testMethod2();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢第二个版本,以便更清楚地了解您想要做什么.
| 归档时间: |
|
| 查看次数: |
256000 次 |
| 最近记录: |