Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java how do i declare a instance variable of another class if i need to pass a variable from the constructor

I want to create an instance of a class which requires currency for its
constructor, however i get the currency passed into the constructor of the class i am creating them in.

public class Owner_Class {
    
    
    

    Controller items = new Controller();
    private Item[][] list = items.getItemList();
    private String currency;
    private coinCollector dispenser = new coinCollector(currency);
    public Owner_Class(String currency) {
        this.currency = currency;

    }

Whenever i run this the currency is just null. Is there anyway to do this or do i need to change how it works

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just.. shift the initialization to the constructor. Java first runs all ‘initializing expressions’, then the constructor. Hence, in your current code snippet, currency begins as null, then new coinCollector(currency) is executed (thus, passing null), then your constructor runs and sets currency – too late.

Hence:

public class Owner_Class {
    Controller items = new Controller();
    private Item[][] list = items.getItemList();
    private Scanner input = new Scanner(System.in);
    private String currency;
    private coinCollector dispenser;

    public Owner_Class(String currency) {
        this.currency = currency;
        this.dispenser = new coinCollector(currency);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading