-1

I don't know when to use a static/non-static variable in a program.

package slides;

public class Person {
        
    String name;
    int age;
    boolean isStaff;
    
    public Person(String name, int age, boolean isStaff) {
        // TODO Auto-generated constructor stub
        
        this.name = name;
        this.age = age;
        this.isStaff = isStaff;
        System.out.println(this);
    }
    
    /*
    public static boolean Staf () {
        
        return isStaff;
    }
    */

}

I understand the difference between the non-static/static variable but I just don't know when to use each. So in the above code, why the function Staf can not be static? (and when it should be static?)

SadSalad
  • 69
  • 2
  • 12

3 Answers3

2

According to the last question, you do not understand the difference. Every non-static method implicitly receives this (as an argument). Static methods are not bound to some instances, so you just can not reference non-static fields. Static stuff can reference only static stuff.

static could be used:

  • For Singleton pattern, for example;
  • Or if you want to utilize class as simple namespace;
  • Or just do not like OOP and going to use COP)
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
1

The static method Staf() is not allowed to return class instance variables because Staf() can be invoked without the class Person instance being created. Therefore, Staf() can only return static variables.

codemax
  • 1,322
  • 10
  • 19
0

You can not access non-static (instance) variables unless you do so with a) a reference to an instance (myPerson.isStaff, which would violate encapsulation) or b) from within a non-static (instance) method.

As to when you should use static, there are many discussions and diatribes on this very website which can easily be found.