• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instantiating a class with non static variables from within a static method  RSS feed

 
Nikolas Nikolaou
Ranch Hand
Posts: 101
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.I'd like to understand why I can create an Instance of a class that contains non static variables within the static main method ?

This program runs fine



Expected non static variable error

 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please indent your code: suggestions here; it makes it much easier to read.
Mark all fields (except global constants) private. You can still run your program because you are still inside the same class.

Lots of people seem to get confused about this.
Your local variable test1 is in a static context. It was made in a static context. But once you have a reference to an object, you have the non‑static context of that object. test1 is static inside the main method, but test1.foo is not static inside test1.
 
Nikolas Nikolaou
Ranch Hand
Posts: 101
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'll take care of my poor to non-existent Indentation !

I think I understand but not quite there yet.
Doesn't this allow someone to kind of bypass the protection of not using a non static Instance variable.
What If I created a utility method and used the object reference to the variable and then that variable changes ?
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nikolas Nikolaou wrote:
Doesn't this allow someone to kind of bypass the protection of not using a non static Instance variable.
What If I created a utility method and used the object reference to the variable and then that variable changes ?


Can you elaborate a bit on the "protection" part? The static modifier is not defining an access level. If the compiler can deference the reference, it will do it. Static variables don't have a concept of a this reference (as it is not particular to a specific instance), so there are some cases where it can't do the deference, and the compiler will tell you when it can't. There is no protection being done here, and hence, nothing being bypassed here.

Henry
 
Nikolas Nikolaou
Ranch Hand
Posts: 101
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand now.I'm thinking about things the wrong way.The purpose Is to be able to use a method In a class that does not have to be Instantiated.
Using a static object reference doesn't Intefer with that.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!