• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static Vs non-static methods  RSS feed

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi EveryOne,

Please can anyone one help me with this doubt...
Is it possible to access both static and non-static fields in a method??

Thanks in advance

Deepthi
 
author & internet detective
Marshal
Posts: 37518
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Deepthi,
Welcome to JavaRanch!

The answer is yes and no. A static method can only access static fields on that class. A non-static method can access both static and non-static fields on that class. And of course both methods could instantiate an instance of the object and access non-static fields on it.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it possible to access both static and non-static fields in a method??

With "field" do you mean a member variable of a class? If that's what you mean then the answer is no, you cannot create member variables inside a method. You declare member variables in the class, not inside a method.

Ofcourse you can declare static as well as non-static member variables in a class.

You can't make a local variable inside a method static.

If you have a question like this then it's a good idea to write a small program and try to compile it, and see what the compiler says.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!