在他的“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 */
也许我有点累了,但是我看不到 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();
}
}
最佳答案
Java 隐含地假定对像这样调用的方法的当前对象的引用。所以
// Test2.java
public class Test2 {
public void testMethod() {
testMethod2();
}
// ...
}
完全一样
// Test2.java
public class Test2 {
public void testMethod() {
this.testMethod2();
}
// ...
}
我更喜欢第二个版本,以便更清楚地说明您想要做什么。
关于java - 在同一个类的另一个方法中调用一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7325779/