Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Newbie Q. Accessing a variable in one method from another.

Reply
Thread Tools

Newbie Q. Accessing a variable in one method from another.

 
 
Mike Barnard
Guest
Posts: n/a
 
      06-22-2010
Hi again all.

Another very basic question from a TOTAL newbie. (I have a book and
I'm getting dangerous to myself now.) However unnecesary some of the
methods below are, I'm doing this to try to learn how to pass
information around.

Q: How does one refer to a variable which was declared in a different
method? My logic was to declare it in the class level block but that
brought the error message:

"G:\java\Projects>javac starnumbers.java
starnumbers.java:28: non-static variable numberStore cannot be
referenced from a
static context
numberStore = new int[number] ;
^
1 error"

I know there's lots of lessons for me to learn yet, but as I only get
about an hour an evening if I'm lucky, it may take some time! This
seems to be the point where I need to learn about static and non
static.











/*
Self tutorial.
Get a user to enter 10 numbers.
display the correct number of stars for each number.
Store the numbers in an array.
Print them all in one go.
*/

public class starnumbers
{
int[] numberStore; // A place to store all of the numbers.
//This was originally in main with 'number'.

public static void main (String[] args)
{
int iterations = 10 ; // number of times to loop.
int number = 0;

initialise (iterations) ;
displayInstructions ();
getAKeypress();
//validateNumber();
//displayStars();
}

public static void initialise (int number)
{
numberStore = new int[number] ;
}

public static void displayInstructions ( )
{
System.out.println("V 1.01 - Instructions");
System.out.println("Use the keyboard to enter single numbers");
System.out.println("You need to enter 10 numbers.\n\n");
System.out.print("Start now...");
}

public static void getAKeypress ()
{
//next bit to study...
}
}

 
Reply With Quote
 
 
 
 
markspace
Guest
Posts: n/a
 
      06-22-2010
Mike Barnard wrote:

> "G:\java\Projects>javac starnumbers.java
> starnumbers.java:28: non-static variable numberStore cannot be
> referenced from a
> static context
> numberStore = new int[number] ;


> public class starnumbers
> {
> int[] numberStore; // A place to store all of the numbers.


static int[] numberStore;

> //This was originally in main with 'number'.
>
> public static void main (String[] args)
> {


This is an easy one. Just make the change that I added above and you're
good to go.

To try to explain this a bit more, static on a method means that the
method isn't attached to any one instance of the class, it's attached to
the class itself. Same for variables. Static means they're attached to
the class (sort like a "global" variable) and not static means the
variable is attached to an instance.

The problem with what you had was a static method was trying to access a
non-static (instance) variable. And you don't have an instance in that
case. So, it fails.

The other thing you could have done, is not make the change I gave you,
then do something like this:

public static void main( String... args ) {
starnumbers sn = new starnumbers();
int number = 5;
sn.numberStore = new int[number];
// ...

See? Now I have an instance, referred to as "sn", so I can use the
instance variable called numberStore with it.

Hope that made sense.

(P.S., also, please use proper capitalization of your class names, e.g.
"StarNumbers".)
 
Reply With Quote
 
 
 
 
Lew
Guest
Posts: n/a
 
      06-23-2010
Mike Barnard wrote:
>> "G:\java\Projects>javac starnumbers.java
>> starnumbers.java:28: non-static variable numberStore cannot be
>> referenced from a
>> static context
>> numberStore = new int[number] ;
>>
>> public class starnumbers {
>> int[] numberStore; // A place to store all of the numbers.
>>
>> static int[] numberStore;
>>
>> //This was originally in main with 'number'.
>>
>> public static void main (String[] args)
>> {


markspace wrote:
> This is an easy one. Just make the change that I added above and you're
> good to go.
>
> To try to explain this a bit more, static on a method means that the
> method isn't attached to any one instance of the class, it's attached to
> the class itself. Same for variables. Static means they're attached to
> the class (sort like a "global" variable) and not static means the
> variable is attached to an instance.
>
> The problem with what you had was a static method was trying to access a
> non-static (instance) variable. And you don't have an instance in that
> case. So, it fails.
>
> The other thing you could have done, is not make the change I gave you,
> then do something like this:
>
> public static void main( String... args ) {
> starnumbers sn = new starnumbers();
> int number = 5;
> sn.numberStore = new int[number];
> // ...
>
> See? Now I have an instance, referred to as "sn", so I can use the
> instance variable called numberStore with it.
>
> Hope that made sense.
>
> (P.S., also, please use proper capitalization of your class names, e.g.
> "StarNumbers".)


There are three basic kinds of variables - static, instance and local.

Static variables belong to the class itself.

Instance variables belong to an instance, or object, of the class.

Local variables are restricted to a block (code between curly braces).

Static methods cannot refer to instance variables.

Code outside a block cannot refer to variables local to that block.

Then there's the matter of 'public', 'protected', package-private and 'private'.

public class FooBar
{
static String belongaType = "This is attached to the class itself";

String belongaInstance = "This is attached to a particular instance";

public static void doSomething()
{
String belongaMethod = "This method cannot use 'belongaInstance'";
System.out.println( belongaType );
// System.out.println( belongaInstance ); // would cause compiler error
System.out.println( belongaMethod );
if ( belongaBlock != null )
{
String belongaBlock = "This is local to the 'if' block";
System.out.println( belongaBlock );
}
// System.out.println( belongaBlock ); // would cause compiler error
}

public void instanceLevel()
{
String belongaLocal = "This method cannot use 'belongaInstance'";
System.out.println( belongaType );
System.out.println( belongaInstance ); // no compiler error
System.out.println( belongaLocal );
if ( belongaBlock != null )
{
String belongaBlock = "This is not the same 'belongaBlock'";
System.out.println( belongaBlock );
}
// System.out.println( belongaBlock ); // would cause compiler error
}

public static void main( String [] args )
{
doSomething();
new FooBar().instanceLevel();
}
}

For a fast introduction to all this, since you have limited time:
<http://java.sun.com/docs/books/tutorial/java/nutsandbolts/index.html>

--
Lew
 
Reply With Quote
 
Mike Barnard
Guest
Posts: n/a
 
      06-23-2010
On Tue, 22 Jun 2010 16:02:27 -0700, markspace <(E-Mail Removed)>
wrote:

Good morning Mark, and thanks.

>Mike Barnard wrote:


>> public class starnumbers
>> {
>> int[] numberStore; // A place to store all of the numbers.

>
> static int[] numberStore;
>


>This is an easy one. Just make the change that I added above and you're
>good to go.


I knew static was relevant but had no concept of what it meant. But
Now I know, I think. See reply to other message below.

>To try to explain this a bit more, static on a method means that the
>method isn't attached to any one instance of the class, it's attached to
>the class itself. Same for variables. Static means they're attached to
>the class (sort like a "global" variable) and not static means the
>variable is attached to an instance.


And as I had / have no instance as such... kablooey.

>The problem with what you had was a static method was trying to access a
>non-static (instance) variable. And you don't have an instance in that
>case. So, it fails.


Heh, wot I said.

>The other thing you could have done, is not make the change I gave you,
>then do something like this:
>
> public static void main( String... args ) {
> starnumbers sn = new starnumbers();
> int number = 5;
> sn.numberStore = new int[number];
> // ...
>
>See? Now I have an instance, referred to as "sn", so I can use the
>instance variable called numberStore with it.


>Hope that made sense.
>
>(P.S., also, please use proper capitalization of your class names, e.g.
>"StarNumbers".)


OK, refreshed on that too.

Thanks for taking the time to reply in a way a tiny brain like mine
can understand!

Mike.
 
Reply With Quote
 
Mike Barnard
Guest
Posts: n/a
 
      06-23-2010
On Wed, 23 Jun 2010 00:57:55 -0400, Lew <(E-Mail Removed)> wrote:

Good morning Lew.

>Mike Barnard wrote:


>There are three basic kinds of variables - static, instance and local.
>
>Static variables belong to the class itself.
>
>Instance variables belong to an instance, or object, of the class.
>
>Local variables are restricted to a block (code between curly braces).
>
>Static methods cannot refer to instance variables.
>
>Code outside a block cannot refer to variables local to that block.
>
>Then there's the matter of 'public', 'protected', package-private and 'private'.


Snip cool example.

>For a fast introduction to all this, since you have limited time:
><http://java.sun.com/docs/books/tutorial/java/nutsandbolts/index.html>


The link is a perfect answer to my question. The phrase "...this tells
the compiler that there is exactly one copy of this variable in
existence, regardless of how many times the class has been
instantiated. " summed it up for me. Static. OK, getting there. Public
etc next.

But this makes me ask a question, that I'll experiment with tonight I
hope.

Q. If I declare such a class-level static variable *within a method*,
bearing in mind the Sun tutorial statement that "...local variables
are only visible to the methods in which they are declared; they are
not accessible from the rest of the class." will that limit what other
code can access the static variable? Will I only be able to see it
from inside the method? Which also makes me ask:

Q. What is the convention for creating such a variable? Place it in
the class, outside methods?

As I said, I'll experiment. And read more!

Thank you.

Mike.
 
Reply With Quote
 
Lew
Guest
Posts: n/a
 
      06-23-2010
Mike Barnard wrote:
> Q. If I declare such a class-level static variable *within a method*,


You can't.

> bearing in mind the Sun tutorial statement that "...local variables
> are only visible to the methods in which they are declared; they are
> not accessible from the rest of the class." will that limit what other
> code can access the static variable? Will I only be able to see it
> from inside the method? Which also makes me ask:


There is no such thing as a static variable declared within a method.

> Q. What is the convention for creating such a variable? Place it in
> the class, outside methods?


You can't.

Variables declared within a method are local, never static or instance.

--
Lew
 
Reply With Quote
 
Mike Barnard
Guest
Posts: n/a
 
      06-23-2010
On Wed, 23 Jun 2010 09:17:10 +0100, Mike Barnard
<(E-Mail Removed)> wrote:

To both Lew and Wayne, thanks for the replies. Hopefully I'll get more
time tonight and play. I'll put a static variable in a method and see
what the error is, etc.


 
Reply With Quote
 
Lew
Guest
Posts: n/a
 
      06-23-2010
Lew wrote:
> * * public void instanceLevel()
> * * {
> * * * *String belongaLocal = "This method cannot use 'belongaInstance'";
>


That String lies. It should have been:

String belongaLocal = "This method *can* use 'belongaInstance'";

Sorry.

--
Lew
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Accessing an instance variable in another method Subashini Kumar Ruby 5 09-23-2009 01:03 PM
Accessing a global variable when there is a local variable in the same name Mohanasundaram C Programming 44 08-23-2004 11:17 PM
accessing class instance variable from instance method David Garamond Ruby 5 06-08-2004 02:26 PM
[Method.invoke] wrapper - accessing arguments passed to user method. Storm Java 1 05-01-2004 11:20 AM
Accessing method object from within a method Vivek Sawant Python 3 02-18-2004 11:09 PM



Advertisments