0

I was curious what public variables actually do. I assumed they work across all classes inside of a package, but apparently that is not the case. I want to know how to carry the ADD, and MULT variables over from the first class into the second class. Here is my code on the first class:

    public class first {
    public static int ADD = 0;
    public static int MULT = 1;
    public static int derp(int x, int x2, int a){
        int septor = 0;
        if(a == 0){
            septor = x + x2;
        }
        if(a == 1 ){
            septor = x * x2;
        }
        return septor;
    }
}

The second class:

public class second {
    public static void main(String args[]){
        int y = first.derp(6,10,ADD);
        System.out.println(y);
    }
}
Austin Gibb
  • 303
  • 1
  • 4
  • 12

3 Answers3

2

As always, the best thing you can do is referring to the docs:

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Class variables are referenced by the class name itself

There is a good example there, follow it and you'll know that you should write first.ADD.

Also please follow Java Naming Convention and replace first with First.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
Maroun
  • 94,125
  • 30
  • 188
  • 241
1

you must use public static fields in other classes like this:

int y = first.derp(6,10,first.ADD);
Hossein Nasr
  • 1,436
  • 2
  • 20
  • 40
0

You can access public static fields using something like this :

Classname.variableName

In you case it would be first.ADD or you can even use instance variable to access them. But it is generally a bad programming practice. Something like this :

first obj = new first();
obj.ADD;

But this is bad programming practice to access static variables using object references. Also you must consider if you can make your static public variables as constants by making them final. This will make sure that other classes accessing the variables do not accidentally or intentionally modify them.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38