Can i create an object outside a method??? Can i also access variables and methods outside an method??? It give error...please help with this method stuff... am not getting what to write inside and outside the method...
Why do we fall? So that we can learn to pick ourselves up.
Ivan Jozsef Balazs wrote:Actually no "rogue" pieces of executable code are possible.
You can have (unnamed) initializing blocks and assignments but nothing much more.
Yes exactly, technically speaking you cannot write anything outside of the method other than declaration. So everything that you put outside of a function is simply for initialization. It's something that's hidden by the compiler so it can be quite confusing
Think of it in this way:
For dynamic field (instance variables):
is the same as:
Yes, you can declare variables outside a method in java. Also, you can create an object and acess variables and methods outside a class. The following example illustrates the same. Suppose you have a class Test and class Sample as follows:
Please always use the code button in your posts. I have edited your post to show how much better it looks, and also corrected the spelling mistake: is should be class not Class.
What you are doing is declaring those fields. Field declarations must be outside methods, otherwise they would turn into local variables. You are allowed to combine a declaration with an initialisation in one line. Unfortunately a class which supports such initialisation may suffer from poor design, e.g. non‑private fields.
What you must not do outside methods (or initialiser blocks) is to write statements. It’s all in the Java Language Specification, which is really easy to read.