【问题标题】:How can I modify a variable throughout the chain of calling of class through it's objects?如何通过它的对象在整个类调用链中修改变量?
【发布时间】:2016-01-27 11:31:53
【问题描述】:

我有 3 节课。

class ClientConnect(){
    URL url = new URL("http:XXX.XX.XX");
    Api api = new Api(url);
    api.checks.count();
}

class Api{
    ...
    URL url;
    Checks checks = new Checks(url);
    public Api(URL url){
        url = new URL(url+"/api");
    }
}

class Checks{
    ...
    public Checks(URL url){
        url = new URL(url+"/checks");
    }
    public void count(){
        url = new URL(url+"/count");
        System.out.println(url);
    }
}

我希望调用 api.checks.count() 的输出为 http:XXX.XX.XX.XX/api/checks/count ,但我得到了空值。如何将修改后的 URL 转入下一个类链。是的,我也可以通过其他方式做到这一点,但我只想使用类的对象链接所有这些。

问题在于 Api 类,我只是希望在创建 Checks 类的对象时将修改后的 URL 发送到那里。

【问题讨论】:

  • Api 的构造函数不应该用传递给它的URL 的实例来初始化Checks 吗?
  • 但是我不能调用count方法,因为api.checks会抛出错误。
  • 基本问题是Checks checks = new Checks(url); 不起作用,因为当变量初始化时url 的实例是null。相反,您需要使用传递给构造函数的参数来初始化Api的构造函数内部的变量

标签: java class variables inner-classes


【解决方案1】:

修改Api 构造函数,并将url 传递给URL 构造函数初始化 url(正如@Jonk 所指出的那样在 cmets 中,它应该是 this.url)。类似的,

URL url;
Checks checks; // <-- url is null.
public Api(URL url){
    this.url = new URL(url+"/api");
    checks = new Checks(this.url); // <-- now url is initialized.
}

【讨论】:

  • 不应该是this.url,否则要重新初始化参数
猜你喜欢
  • 2019-09-18
  • 2016-05-10
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多