Static private variable

Hello,
I was wondering, what is the use of static? I was doing a class that look like:
public class TheClass{
  private static String a;
  public TheClass() {
  public Seta(String bb){
    a = bb;
  public String GetA(){
     return a;
Then if in another class I do:
TheClass bb = new TheClass();
bb.SetA("BBBBB");
TheClass cc = new TheClass();
cc.SetA("CCCCC");
println(bb.GetA());
println(cc.GetA());both println output CCCCC. Does that mean that a static variable in a class will be share by all instace of that class?
So I could have a static variable status, that when updated or change could affect the beavior of all instatiated object in the JVM?
thanks,

If a variable is declared static, there exists exactly one incarnation of the variable, no matter how many instances (possibly zero) of the class may eventually be created. A static variable, sometimes called a class variable, is incarnated when the class is initialized.
A variable that is not declared static (sometimes called a non-static variable) is called an instance variable. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.
If a variable is declared private, then access is permitted only when it occurs from within the class in which it is declared.

Similar Messages

  • Accessing a private variable from a public method of the same class

    can anyone please tell me how to access a private variable, declared in a private method from a public method of the same class?
    here is the code, i'm trying to get the variable int[][][] grids.
    public static int[][] generateS(boolean[][] constraints)
      private static int[][][] sudokuGrids()
        int[][][] grids; // array of arrays!
        grids = new int[][][]
        {

    Are you sure that you want to have everything static here? You're possibly throwing away all the object-oriented goodness that java has to offer.
    Anyway, it seems to me that you can't get to that variable because it is buried within a method -- think scoping rules. I think that if you want to get at that variable your program design may be under the weather and may benefit from a significant refactoring in an OOP-manner.
    If you need more specific help, then ask away, but give us more information please about what you are trying to accomplish here and how you want to do this. Good luck.
    Pete
    Edited by: petes1234 on Nov 16, 2007 7:51 PM

  • Private variable issues

    Hello,
    While studying I have come up with this problem a few times and was wondering if you could help me.
    I am currently working with linked list examples and the variables used have default package access. I am however told that the variables should normally be declared private.
    So I made a kinda dummy class which shows my problem.
    public class Private
         private Private unreachable;
         private String greating="hello";
         public Private()
              unreachable = null;
              greating="";
         public String getGreating()
              return greating;
         public Private getReach()
              return unreachable;
    public class PrivateWork
         private String differentGreating;
         private Private reachMe;
         public PrivateWork()
              differentGreating="";
              reachMe=null;
         public void changeGreating(String change)
              Private p = new Private();
              p.greating = change;     //produces "greating has private access in the class Private" error
              p.getGreating() = change; //produces "unexpected type" error
              reachMe = p;
    public class TestPrivate
         public static void main(String[]args)
              PrivateWork p = new PrivateWork();
              p.changeGreating("Good Morning");
    }I know that by making the Private class an inner class of PrivateWork I can keep the variables declared private and the "p.greating = change;" will work.
    However is there another way I can access the "greating" variable from the changeGreating(String change) method in the PrivateWork class.

    I am currently working with linked list examples and the variables
    used have default package access.What variables are you referring to?
    p.greating = change;     //produces "greating has private access in the class Private" error That one should be pretty obvious because it is the definition of private: you can't use objects of the class to access private variables.
    By the way, "greating" is spelled greeting.
    p.getGreating() = change; //produces "unexpected type" errorI'm not sure about that one. But, you can split that statement up into two lines and you won't get a compile error:
    String gr = p.getGreating();
    gr = change;However, I don't think that is going to do what you expect. Try to predict the output of this example:
    class Private
         private String greeting="hello";
         public String getGreeting()
              return greeting;
    public class AATest1
         public static void main(String[]args)
              Private p = new Private();
              String gr = p.getGreeting();
              gr = "Goodbye";
              System.out.println(p.getGreeting()); //Output??
    }

  • Static class variable doesn't store ?

    Hi,
    I'm a beginner in java.
    I defined a static class variable (nodes) in th following code :
    public class MySOMapp extends javax.swing.JFrame {
         private static final long serialVersionUID = 1L;
         private static SOMTrainer trainer;
         private static SOMLattice lattice;
         private static SOMNode nodes;
         private static Hashtable nwordf; 
         public MySOMapp(String args[]) {
              SOMNode nodes = new SOMNode();          //.....But a method of this class, nodes comes null. methos definition :
    private void makesame() {I don't understand why the nodes is null in makesame method which is in the same class with nodes ?
    thanks,
    Yigit

A: static class variable doesn't store ?

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

thankyou. I solved the problem. But why static fields
are not good idea ? How can i get rid of these...Remove the static word :) Seriously, try to develop a technique to get swiftly out of the static main method. Like this:
class MyClass {
    MyClass() {
        // Your code here instead of in main method.
    public static void main(String[] args) {
        new MyClass();
}

  • Multithread & private variables ?

    Hi,
    I would like to know if we can have private variables when we have multiple threads from the same class : in fact even if i declare a variable private when it is changed it is for all threads together, and for the future thread too : how can this be done please ???

    Hi !
    I'm sorry but really it doesn't work : i'm calling this servlet many times using get and st is everywhere set to carine...then I'm calling the post method that set up st to canard in all threads...but if i call a get again then st is set to carine again and everywhere : that means it is not private variables for each threads, I'm sorry but really I would like to know to do that properly....what's wrong ????
    Thank you for your help
    package servlettest;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class carine
        extends HttpServlet {
      private static class ThreadState {
        public String owner;
      private static ThreadLocal state = new ThreadLocal() {
        protected Object initialValue() {
          return new ThreadState();
      ThreadState st;
      public void init() throws ServletException {
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws
          ServletException, IOException {
        st = (ThreadState) state.get();
        st.owner = "carine";
        synchronized (this) {
          while (true) {
            System.out.println("st contains : " +  st.owner);
            try {
              this.wait(2000);
            catch (InterruptedException ex) {
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws
          ServletException, IOException {
        System.out.println(st.owner);
        st.owner = "canard";
    }

  • Non-static ThreadLocal variables

    I want to know what is the actual problem in having non-static ThreadLocal variables ? I am looking for some insights. Java doc says that typically ThreadLocal variables are private and static but does not mention that it has to be mandatorily static and does not provide the reason behind the recommendation for being static. Can anyone please clarify ?

    What if I have a code like this i.e. a singleton object having reference to a non-static ThreadLocal variable ?
    public class ThreadLocalTest {
         private ThreadLocal<Integer> tlocal;
         private static final ThreadLocalTest tester = new ThreadLocalTest();
         private ThreadLocalTest() {
              this.tlocal = new ThreadLocal<Integer>();
              log("Created ThreadLocalTest instance");
         public static ThreadLocalTest getInstance() {
              return tester;
         public void setValue(int i) {
              this.tlocal.set(new Integer(i));
              log("Set value = " + i);
         public int getValue() {
              int i = this.tlocal.get();
              log("Got value = " + i);
              return i;
         public static void main(String[] args) {
              for(int i = 0; i < 2; i++) {               
                   Thread t = new Thread(new Runner());
                   t.setName("Thread-" + i);               
                   t.start();
         public static void log(String msg) {
              String thread = Thread.currentThread().getName();
              String date = new java.util.Date().toString();
              String prefix = "[" + thread + "] " + date + ": ";
              System.out.println(prefix + msg);
         static class Runner implements Runnable {          
              public void run() {
                   for (int i = 0; i < 100; i++) {
                        ThreadLocalTest tester = ThreadLocalTest.getInstance();
                        tester.setValue(i);
                        tester.getValue();
    Edited by: radiatejava on Oct 22, 2012 4:56 PM

  • Overloading a static final variable

    This is a question from a book. I am not sure of overloading a constructor with a static final variable. Here is the class
    public class Pizza{
    private static final double cost_price = 10.0;
    String topping;
    double price;
    }next, the question wanted me to create a constructor to override the topping and the price of the original constructor so i did
    public Pizza(String t, double p){
    topping = t;
    price = p;
    }Next it wants me to override the constructor another time only by receiving one parameter which is the topping by calling the above constructor but instantiate the price to the constant price which is the final static variable.
    public Pizza(String t){
    cost_price = p;
    this(t, p);
    }I dont know if the above solution that i did is correct as it maybe have some correction to be made because of the static final variable or the above code does not work. Please help me to verify thank you

    Sorry but what does it means? Do you have any
    solution? I would appreciate it .The last one should look like this:
    public Pizza(String t){
       this(t, cost_price);
    }

  • Encapsulation hide private variable

    As below code showing that you cannot directly access the private variable as i understood, Pls guide.
    public class EncapsulationDemo{
       private int ssn;
       private String empName;
       private int empAge;
       //Getter and Setter methods
       public int getEmpSSN(){
       return ssn;
       public String getEmpName(){
       return empName;
       public int getEmpAge(){
       return empAge;
       public void setEmpAge(int newValue){
      empAge = newValue;
       public void setEmpName(String newValue){
      empName = newValue;
       public void setEmpSSN(int newValue){
      ssn = newValue;
    public class EncapsTest{
       public static void main(String args[]){
       EncapsulationDemo obj = new EncapsulationDemo();
      obj.setEmpName("Mario");
      obj.setEmpAge(32);
      obj.setEmpSSN(112233);
       System.out.println("Employee Name: " + obj.getEmpName());
       System.out.println("Employee SSN: " + obj.getEmpSSN());
       System.out.println("Employee Age: " + obj.getEmpAge());

    As below code showing that you cannot directly access the private variable as i understood,
    That code shows NO such thing.
    Tell us what line you think you are 'directly' acessing a private variable. Looks like you are using accessors for ALL accesses to me.
    See The Java Tutorials trail 'What Is an Object'. It discusses encapsulation.
    What Is an Object? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Co…
    Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

  • Accessing Private variable using reflection

    Is someone have code snippet for accessing private varaible using reflection
    Here is my code snipper
    import java.lang.reflect.Field;
    public class test1234 {
    private String t;
    public test1234() {
    public String show() {
    return t;
    import java.lang.reflect.Field;
    public class Test123 {
    public Test123() {
    public static void main(String[] args) {
    test1234 test12341 = new test1234();
    try {
    Class cls = test12341.getClass();
    Field fld = cls.getField("t");
    fld.set(test12341, "12");
    catch (Exception e) {
    System.out.println(e.getLocalizedMessage());
    I am getting exception when i try to access.
    java.lang.NoSuchFieldException
         at java.lang.Class.getField0(Native Method)
         at java.lang.Class.getField(Class.java:826)
         at Test123.main(Test123.java:24)
    Thanks in advance

    Thanks for your response. After setting accessible to true i can able to set into private variable.
    Thanks a lot.

  • Private inner class and static private inner

    Hi,
    I understand the concept and usage of inner classes in general.
    When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
    Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
    Thanks in advance.

    user1995721 wrote:
    When should we go for a private inner class and when for a static private inner class?
    I can make the program work by using either normal inner class or static inner class, however would like to know which is better
    If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
    If the inner class needs to access non-static fields or methods from the containing class instance
    the inner class has to be non-static.

  • JDEVELOPER 10G, ADF BC: Passivate static instance variables in AM?

    I understand the need to passivate/activate instance variables but what about static instance variables within an application module?
    Thanks,
    Wes

    Static variables - being class variables and not instance variables - persist without a need for passivation. Is there a particular reason or scenario why to use static variables? You have to consider that since all AM instances will share it, changing it in one AM instance - i.e. one user session - will affect all other AM instances - i.e. all other user sessions! You also have to consider the implications of multithreading when attempting to modify the static variable.

  • Enforce setting private variable in subclass with abstract method

    Hi,
    Is this something that is common usage/practice?:
    public abstract class Base {
        private int importantPrivateVariable = setImportantPrivateVariable();
        protected abstract int setImportantPrivateVariable();
    }I would like to enforce the extender of the class to set a private variable, but as there is no abstract variable in java, I can only use a method for it.
    Thanks,
    lemonboston
    Edit: the variable could be protected as well, I suppose this is not important here, but correct me if I am wrong

    lemonboston wrote:
    Hi,
    Is this something that is common usage/practice?:I don't think that's so common, but that's code easily understandable. However there are several problems with this approach:
    public abstract class Base {
    private int importantPrivateVariable = setImportantPrivateVariable();
    protected abstract int setImportantPrivateVariable();
    }I would like to enforce the extender of the class to set a private variableThat's no what your code implements: your base class forces the subclasses to return an int value, and the Base class uses that value to assign it to the variable.
    Therefore the method should be called get<Something> (e.g. <TT>getInitialValueOfImportantVariable()</TT>+ to have a naming consistent with its signature (it returns a value, whereas a regular setter method should declare a void return type: <TT>protected abstract void setImportantPrivateVariable(int someValue);</TT>).
    Edit: the variable could be protected as well, I suppose this is not important here,Well, yes, this is "important" - at least, there a noticeable difference: the variable being private, the base class is free to handle it as it sees fit (e.g., assign the value at construction time and never modify it afterwards). If the variable was protected, the subclass could modify in ways and at times not known by the base class.
    but correct me if I am wrongThere's a trap in this construct: the method is called in the variable initializer, that is, behind the scenes, approximately during the execution of the Base class constructor, so before the subclass constructor. So, you are calling a method on an object that is not fully initialized (e.g. some of its attributes may still be <TT>null</TT> at this stage). There is a rule that discourages such situations, that goes something like "don't call non-private and non-final methods from a constructor".
    To avoid this trap, two options:
    - require an int argument in the Base class's constructor , as was suggested above
    - don't get and set the value of the important variable in the initializer or constructor code, but from a special method in the base class instead:
    public abstract class Base {
        private int importantPrivateVariable; // default value is zero
    // or alternatively:
    //    private int importantPrivateVariable = ...; // Some default value
        protected abstract int getImportantPrivateVariable();
        public void initializeImportantPrivateVariable() {
            importantPrivateVariable = getImportantPrivateVariable();
    }That construct is a degenerate form of a common design pattern known under the name of Template Method (where a base class method calls generally several subclass methods in a specified order and with a specified chaining, leaving it to the subclass to implement the details of the methods).
    The drawback is that the client code (the one that uses the Base instance) has to know when to call that initialization method, whereas the constructor-based initialization lets the client code free to not care at all.
    Much luck,
    J.

  • Static class variable

    Folks:
    I am little confused by static class variables in Java. Since Java doesn't have global varaibles it uses static variables instead. Please take a look at the following code and please tell me what goes wrong.
    /********** CONTENT OF Stack.java ***********/
    import java.util.Stack;
    public class StackClass
    {   static  Stack stack = new Stack (); }
    /********** CONTENT OF Test1 .java ***********/
    public class Test1
    public static void main( String[] args )
    StackClass.stack.push("Hello World");
    /********** CONTENT OF Test2.java ***********/
    public class Test2
    public static void main( String[] args )
    System.out.println( "Top on stack is " + StackClass.stack.peek() );
    I execute the above programs in the sequence of StackClass.java, Test1.java and Test2.java. I think in Test1.java after I push one element to the stack it should still be in the stack in Test2.java But I got :
    java.util.EmptyStackException
         at java.util.Stack.peek(Unknown Source)
         at Test2.main(Test2.java:16)
    Exception in thread "main"
    Can anybody give me a hint?
    Thanks a lot !

    After you run StackClass, the JVM (java.exe) ends and all the classes are unloaded including StackClass
    When you run Test1, StackClass is loaded, an item is pushed on the stack, and then the JVM exits and all classes are unloaded including StackClass
    When you run Test2, StackClass is loaded, and you get an error because the StackClass which was just loaded has no items in it.

  • Equivalent of "C static local" variable?

    Hi!
    I am trying to write a sub-VI that has multiple call modes
    (init, do1, do2) and needs to remember some variables set in the
    'init' call. When I try the straightforward way of just placing
    indicators as temporary variables on the front panel, these seem
    to reset to the default values every time the VI is called.
    Is there any equivalent of the static local variables used in C?
    Or do I have to use GLOBAL variables?
    Rudolf

    There are several solutions:
    1. Global variables.
    You can create global variable for each of your temorary variables. This is easy to do but I think it's not very convivient way to pass data.
    2. One Global variable.
    If you have many temporary variables you can organize them into cluster and create only one global variable for this cluster. Then you have to read and write this cluster in your SubVI every time you change any of your temporary variables.
    3. Pass data to/from your SubVI.
    If you look at the most of LV VIs you will see that very often they have some practically identical input and output nodes. For example "AI Start.vi" has " task ID in' and "task ID out" nodes. You can make the same thing. Let your subVI reads and writes some cluster of your tempora
    ry variables through its input and output nodes. So you will have the access to this variables in any place ofyour main VI. Also you can change and create your own clusters of temp variables in your main VI. And also you will get the ability to pass these data to your subVI using local variables or shift registers or sequence locals in your main VI
    I think that the last way is the most useful.
    Good luck.
    Oleg Chutko.

  • [svn] 3438: Forgot to change a private variable to protected in my previous check-in.

    Revision: 3438
    Author: [email protected]
    Date: 2008-10-01 08:27:31 -0700 (Wed, 01 Oct 2008)
    Log Message:
    Forgot to change a private variable to protected in my previous check-in.
    Modified Paths:
    blazeds/trunk/modules/core/src/flex/messaging/services/messaging/ThrottleManager.java

    Hi Ignacio ,
    To change the username you should follow these steps ;
    1-You should have to use nQUDMULGen command to export your rpd into a file.Go to ...OracleBI\server\Bin
    ex. nQUDMULGen -u Administrator -p Administrator -r C:\OracleBI\server\repository\paint.rpd -o c:\paint.txt
    2-After importing try to find your user and change its settings.
    3-Then import it back to your rpd.
    ex. nQUDMLExec -u Administrator -p Administrator -i c:\paint.txt -b C:\OracleBI\server\repository\paint.rpd -o C:\OracleBI\server\repository\paint2.rpd
    The new rpd is going to be created (paint2).Test the new rpd.If its OK.Then replace with your original rpd.
    I hope this method works...

  • Maybe you are looking for

    • Free Transform Problem in CS5.1

      I am haveing an issue when trying to use the Free Transform funtion in Photoshop CS5.1. After pressing command+T, the bounding box appears, but when I attempt to resize, the program becomes unresponsive. After a minute or two I can cancel the Free Tr

    • I am trying to down load purchased music, but is says I have to Authorize my mac first. How do I do that ?

      I am trying to load music I have purchased on a different PC to my MAC. it says I have to authorize the Mac first. does someone know how I do that

    • BP ESS for R/3 4.7 Enterprise backend

      Hi Experts, I have an EP 6 installation on WEBAS 6.40 and I am trying to install the ESS BP compatible with R/3 4.7 Enterprise. I have downloaded BPESS46C504_0-20000613.ZIP from SAP Service Martketplace. While trying to import the content of the ZIP

    • SOAP Header Java

      hi, one question: i need a header like this: <SOAP-ENV:Header> <mm:MMHeader :xmlns: mm=�http://www.ericsson.com//MMS/mm7�           SOAP- ENV:mustUnderstand="1"> <mm:MessageType>MM7_SUBMIT.REQ</mm7:MessageType> <mm:TransactionID>5</mm:TransactionID>

    • Analogue output digital output

      Hello, I managed to create my VI in the proper way I think. I am trying to send a ttl every time my analogue output crosses zero. All whats left now is to transform the analogue data into a digital data and input it into the dammx write for the DO li