• Post Reply Bookmark Topic Watch Topic
  • New Topic

Initializing  RSS feed

 
Lucky Singh
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have the following class.
public class Hello
{
int num = 0;
String flower;
public static void main(String args[])
{
num = 10;
flower = new String("Roses");
Hello sb = new Hello();
sb.print();
}
public void print()
{
System.out.println(num + flower);
tryAgain();
}
public void tryAgain()
{
System.out.println(num + flower);
}
}
My question is-
1. I have declared num as a class variable. Will any changes made to it by
a member function automatically alter the valye of num?
2. Hence if some other method like tryAgain tries to access num, what will it print?
3. In order to make num accessible everywhere in the class, although changed in value in a method, what should I do?
Thanks.
 
Sloan Bowman
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One thing to note is that you should always declare any class variables as private so only the declared class can access the variables. Or if you are using packages and want to be able to access the variables use protected. To answer your question if you have int num = 0; declared as a class variables then yes you can access it and modify it from any method in the class. For example:


Hope this helps. Let me know if you need anything else.
 
Lucky Singh
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!