tanmayghosh2507
tanmayghosh2507

Reputation: 773

How can I modify a variable throughout the chain of calling of class through it's objects?

I have 3 classes.

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

I want the output of the calling of api.checks.count() to be http:XXX.XX.XX.XX/api/checks/count , but I am getting null. How can I carry forward my modified URL into the next chain of class. Yeah, I can do it in other ways too, but I want to chain all these using objects of the classes only.

The issue lies in the Api class, I just want the modified URL to be sent there while creating the object of Checks class inside.

Upvotes: 0

Views: 86

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201497

Modify the Api constructor, and pass url to the URL constructor after you initialize url (and as pointed out by @Jonk in the comments, it should be this.url). Something like,

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.
}

Upvotes: 3

Related Questions