• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Initializing

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the reply.
 
reply
    Bookmark Topic Watch Topic
  • New Topic