Solved

global variable ....

Posted on 2004-09-22
11
204 Views
Last Modified: 2010-03-31
Hi experts,

  I have some java files with the following structure :

A.java :
public class A{
 ...
}

--------------
TestA.java
public class TestA{
   ...
   public static void main(...){ ...
  }
}
-------
  How do I set a global variable which can be read by A.java and TestA.java ??? Thanks !
0
Comment
Question by:meow00
  • 2
  • 2
  • 2
  • +4
11 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 12120725
Avoid "Global variables" if possible
Why should you need it?
0
 
LVL 35

Accepted Solution

by:
girionis earned 150 total points
ID: 12120726
You can have an interface and make them implement this interface:

public interface GlobalVariable
{
    public static int global = 10;
}

public class A implement GlobalVariable
{
   System.out.println(global);
}

public class TestA implements GlobalVariable{
   System.out.println(global);
}
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 12120732
You can't.

You could make a static 'variable' and create an instance of class A in class TestA

public class A {
   public static int variable;
   ...
}

public class TestA {
   private A myA = new myA();
   ...
   public static void main(...){
     myA.variable = somevalue;
   }
   ...
}

-r-
0
 
LVL 35

Expert Comment

by:girionis
ID: 12120736
>public class A implement GlobalVariable

should be

public class A implements GlobalVariable
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12120796
Be aware though that this way you don't have a variable you can assign values to...
Just read it
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 92

Expert Comment

by:objects
ID: 12120810
> How do I set a global variable which can be read by A.java and TestA.java ???

Java doesn't have global variables.
Use a class (static) variable as mentioned above.

A.java :
public class A{
   public static int X;

 ...
}

--------------
TestA.java
public class TestA{
   ...
   public static void main(...){

     // to access use
     int x = A.X;

     ...

  }
}
0
 
LVL 3

Expert Comment

by:granbajo
ID: 12120846
Another way of doing it is to define a global variable in one of the classes, and methods to set it and read it, and call those methods from the second class.  Something like this:

A.java :
public class A{

  int globalInt;

  public int getGlobal() {
    return(globalInt);
  }

  public void setGlobal(int i) {
    globalInt = i;
  }
 ...
}

--------------
TestA.java
public class TestA{

A a
   ...
   public static void main(...){ ...
     a.setGlobal(8);
     int x = a.getGlobal();
     
  }
}
0
 
LVL 24

Expert Comment

by:sciuriware
ID: 12121455
Everybody who says that JAVA doesnot have global variables has never read the documentation.
(fortunately not everybody is referred by this)
See the constants in Math (PI, E) : who can live without them?
The difference to your own wanted variables is omitting the keyword 'final'
;JOOP!
0
 
LVL 92

Expert Comment

by:objects
ID: 12121477
> See the constants in Math (PI, E) : who can live without them?

constants and global variable are different things :)
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 12121513
so therefor static final public classattributes should be called 'globals'?
0
 
LVL 21

Assisted Solution

by:MogalManic
MogalManic earned 150 total points
ID: 12121630
Most of the above comments are correct.  Global variables are NOT part of Object Oriented programming(OOP) and you should avoid them like the plague(like goto's).  Instead you should think of how the data is to be used and create objects that implement the pattern that best fits the usage.  Here are some examlpes.

 -If the value is a constant (i.e. PI, ERROR_MESSAGE_TEMPLATE, ...) create an interface containing the constant values.
     public Interface ApplicationConstants {
        //These probably should be seperated by category
        public final String ERROR_MESSAGE_TEMPLATE="You are a dummy,  why did you do that!?!?!?";
        public final int INCHES_PER_MILE=5280;
        public final double CM_PER_INCH=2.83;  //todo:look up the CORRECT value
    }
 -If the value is a applictation configuration, store them in properties (e.g. defaultWindowSize, dbConnectURL, ...)
 -If the value is part of collection of services, then use the Singleton pattern
      public class Singleton
      {
            private Singleton ref;
            private Singleton()
            {
            }

            public static void getInstance()
            {
                 if (ref==null) {
                      ref=new Singleton();
                 return ref;
            }

            public int getSingletonValue()
            {
                    return this.x;  //This is some computed or queried value that the singleton produces
             }
      }

Don't be afraid of creating lots of classes.  It is better to have many easy to understand class relationships, then one gigantic class that is hard to maintain.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now