Skip to main content

Life of variables

3 replies [Last post]
Joined: 2008-08-24

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-06-03

Hi jhipp,

I haven't used VB, so I can't comment there. The behavior you are describing sounds as if you have created a local variable, which only "lives" so long as the method is executing. When the method exits, the state of the local variable is lost. There are instance variables, which sound like they should do what you want -- the state of an instance variable is unique to each instance of the class. Then there is the class variable. This is shared across ALL instances of a class.

So it _sounds_ like you are using a local variable when you really want an instance variable. Or maybe even a class variable. (Class variables are declared the same way as instance variables, but prefixed with "static".)


Joined: 2008-08-24

Thank you both for your kind replies.

On reflection the tutorial is fine as a core thread. I guess the answer to my question is given in the following sentence:

“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”, which is on this page:

I still think it would be nice for side threads, for newcomers from other languages, perhaps more sloppy or less disciplined languages, really spelling how the theory of Java, as set out in the core thread, translates into practical.

I know there is a thread:,

which gives a practical example of programming with the GUI, But the text admits this example is almost trivial. It would be nice to have an example of code, which does a little more than simply plonks text in a text box.

As I said in my original post, I needed variables to persist after the code in the button had finished executing. After much navel contemplation I realised that the Java programming model required me store these variables in field of an abject. This in turn required me to create a class, and to put an instance of that class on the form.

In the apparent absence of a tutorial explaining exactly how to import custom classes to a NetBeans form I was floundering around in the dark a bit, as described in the following thread:

If anyone knows of a tutorial on this topic, I’d still be quite interested to read it.

Many thanks again.

Joined: 2006-02-02

I've done VB in my day too. Are you talking about VB 6 or The behaviour you describe should also work in Java if you have declared instance variables in your class. Could you give me some sample code to show what you are trying to do?