Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

java - Calling a method inside another method in same class

In page 428 (the chapter about Type Information) of his "Thinking In Java, 4th Ed.", Bruce Eckel has the following example:

public class Staff extends ArrayList<Position> {
    public void add(String title, Person person) {
        add(new Position(title, person));
    }
/* rest of code snipped */

Maybe I'm a bit tired, but I can't see how the call to add() inside the add() method works. I keep thinking that it should have a reference, or be a static method (and I can't find a static add() in ArrayList or List). What am I missing?

I just tested for myself, and found that this works:

// 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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Java implicitly assumes a reference to the current object for methods called like this. So

// Test2.java
public class Test2 {
    public void testMethod() {
        testMethod2();
    }

    // ...
}

Is exactly the same as

// Test2.java
public class Test2 {
    public void testMethod() {
        this.testMethod2();
    }

    // ...
}

I prefer the second version to make more clear what you want to do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...