• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

class and instance variables

 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
my program is given below:

the output is :
value of j is 0
value of cv.s is 0
value of cv.p is null
value of cvs.s is 0
value of cvs.p is null
value of cv.s is 1000
value of cv.p is firststring
i have initialized the values of s and p. i was under the impression that class variables belonged to the class and not to the instance and it did not matter if they were prefixed with the instance name their values would still remain the same. Am i missing something basic here???
[ Jess added UBB [CODE] tags to preserve whitespace. ]
[ October 01, 2002: Message edited by: Jessica Sant ]
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you're getting a bit confused by local variables, static variables and non-static variables.
int j is a local variable -- it belongs only to the method it is defined in.
int s and String p are non-static variables -- it belongs to the instance of a class. You have created two instances: cv and cvs.
you don't have any static variables defined. Try modifying one of the non-static variables to use the 'static' modifier, and see what happens, I think you'll get more the behavior you expected. But realize, its VERY bad practice to access a static variable through an instance.
 
charu latha
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the information. I was under the impression that if i declared a class variable then it automatically became a static variable. I think that is not the case. I did my program again with static prefixed the class variables and it worked as i wanted it to.
 
Create symphonies in seed and soil. For this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic