在同一个类的另一个方法中调用一个方法 [英] Calling a method inside another method in same class

查看:78
本文介绍了在同一个类的另一个方法中调用一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bruce Eckel在他的"Thinking in Java,4th Ed."的第428页(有关类型信息的章节)中,具有以下示例:

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 */

也许我有点累,但是我看不到add()方法中对add()的调用是如何工作的.我一直认为它应该有一个引用,或者是一个静态方法(并且我在ArrayList或List中找不到静态add()).我想念什么?

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();
    }
}

推荐答案

对于这样的方法,Java隐式假定对当前对象的引用.所以

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

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

    // ...
}

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

    // ...
}

我希望使用第二个版本来更清楚地说明您要做什么.

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

这篇关于在同一个类的另一个方法中调用一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆