简体   繁体   中英

Accessing Static variable from one class to another but getting incorrect value

This is my first question on stackoverflow,

I want to access static int variable of one class in another class but when i access this variable in another class it always gives me "zero" .

This is First class :

package kk;

public class ag {
    public static int n=0;

    public static int as()
    {
        return n;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        n=3;
        n=n*5;
        System.out.println(n);
    }


}

Here the output is 15 ie n=15 here.

Second class:

package kk;

public class ah extends ag {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //ag aa =new ag();
int k =ag.as();
System.out.println(k);
    }

}

In this am trying to access the static variable n from First class but getting 0 as output but i want 15.

You are getting 0 because that is the initial value of n in the first class ag . n is only changed to 15 when ag 's main() method is executed, but you are currently not doing this.

You could call the ag.main() method "manually" as part of the main() method of ah , eg:-

ag.main(null); // <- new code
int k =ag.as();
System.out.println(k);

This will set n to 15, but is not the best way to do this.

Java keeps the values maintained for variables only for execution. When 1st program finishes execution, this object no longer exists. Hence for 2nd class execution this value will not be present & initialized to 0 according to definition.

If you really want it to be 15 then initialize it to 15.

package kk;

public class ag {
    public static int n=3*5;

    public static int as()
    {
        return n;
    }
}

OR

call the main() of ag before calling as()

package kk;

public class ah extends ag {

    public static void main(String[] args) {
        ag.main(args);
        int k =ag.as();
        System.out.println(k);
    }
}

Your calculations:

n=3; n=n*5;

are evaluating in main() method of class ag, so it has no impact on class ah where you have second main() method - it looks like you have to programs, not just one.

@anju, One more thing to consider ...

When creating static variables, the compiler sometimes substitutes the value to save time. Especially when you use the keyword final. That means when you compile, it will substitute the current value in your secondary (or usage) classes. If you change that value, you need to recompile ALL usages or compile everything, otherwise, they will have the old value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM