How do i solve this non-static and static variables accessing through methods for once and for all?

StackOverflow https://stackoverflow.com/questions/22656217

  •  21-06-2023
  •  | 
  •  

Question

I have always had problems with accessing private varibles in a class through a method to another class, for instance now i have this problem :

i have this variable in say class Hello1 :

    private Item[][] bankTabs;

and i want to access it through another class say hello2, so i made a public method in Hello1 that is this :

    public int amountOfItemInBank(int id) {
    int amountInBank = 0;

    for(int i = 0; i < bankTabs.length; i++) {
        for(int i2 = 0; i2 < bankTabs[i].length; i2++) {
                if (bankTabs[i][i2].getId() == id)
                    amountInBank = bankTabs[i][i2].getAmount();
        }
    }
         return amountInBank;

}

but when i want to access it through Hello2, it tells me the method is not static, and when i make it static, the variable bankTabs in amountOfItemInBank do not work and i get a lot of errors.

so when i go to Hello2 class, and i try to call this method like this :

 Hello1.amountOfItemInBank(50);

how can i solve this?

Was it helpful?

Solution

Either make an object of Hello1 class and then access the method

Hello1 obj = new Hello1();
int returnValue = obj.amountOfItemInBank(50);

or declare both the variable bankTabs and method amountOfItemInBank as static in Hello1 class and use Hello1.amountOfItemInBank(50); as you did earlier.

Also, read more here Understanding Class Members to clear your understanding and then you can solve the problem for once and for all.

OTHER TIPS

Static METHODS can be called on class, and not object, like

Hello1.amountOfItemInBank(50);

To call a non-static method, you need an object of a class:

Hello1 hello = new Hello1();
hello.amountOfItemInBank(50);

The method doesn't have to be static to make use of a static field in such way. Declaring a field as static lets you use its value (if it's public) without making object of a class:

Item[][] items = Hello1.bankTabs;

or by a method call (if it's private):

Hello1 hello = new Hello1();
Item[][] items = hello.getBankTabs();


// in your class
private static Item[][] bankTabs;
public Item[][] getBankTabs() {
    return bankTabs;
}

If you do not need to access the field without instantiating the class, you probably do not want to make that variable static.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top