Home > OS >  Java how do i declare a instance variable of another class if i need to pass a variable from the con
Java how do i declare a instance variable of another class if i need to pass a variable from the con

Time:04-10

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

CodePudding user response:

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