|
![]() |
Always learning Java, currently using Eclipse on Fedora.
Linux user#: 501795
jay sugrue wrote:
And got no compilation warning, yet to my eyes this also references a non-static variable from a static context ?
Always learning Java, currently using Eclipse on Fedora.
Linux user#: 501795
jay sugrue wrote:Sorry Greg will do...Henry, forgive me here I'm pretty fresh to Java but what do you mean by the static method not accessing the instance variable ?
jay sugrue wrote:"You've got two x variables - one instance variable and one method argument. And it's not using the one you think it is. "
- I understand that one is an instance variable and the other is a method argument but I'm not sure I know what you mean by the static method not using the instance variable - from public static void...onwards, including everything between the emboldened braces of this method, isn't this all considered a 'static context', ie. including System.out.println(x); and therefore unable to take instance variables ?
jay sugrue wrote:...but I'm not sure I know what you mean by the static method not using the instance variable - from public static void...onwards, including everything between the emboldened braces of this method, isn't this all considered a 'static context', ie. including System.out.println(x); and therefore unable to take instance variables ?
jay sugrue wrote:...why then can an instance variable be passed into this static context - is that not against the rules ?
jay sugrue wrote:Henry, in regards to your reply, how would the compiler know what instance x is referring to ?
Java Language Specification wrote:A declaration d of a local variable or exception parameter named n shadows, throughout the scope of d, (a) the declarations of any other fields named n that are in scope at the point where d occurs, and (b) the declarations of any other variables named n that are in scope at the point where d occurs but are not declared in the innermost class in which d is declared.
Gaurangkumar Khalasi wrote:
jay sugrue wrote:...why then can an instance variable be passed into this static context - is that not against the rules ?
Q.1). Have you know about "Parameter Passing" in java?
Your main issue: non-static variable x cannot be referenced from a static context.
Q.2). What is the meaning of "referenced"?
If you get the information about Q.1 and Q.2, you will get the idea...![]()
Henry Wong wrote:... There is a common sense reason why instance variables can't be accessed from a static context -- the static context doesn't have access to a "this" variable. If you understand the reason, then you can understand how you can get around the issue, either by using another instance besides the "this" instance, or passing the value via another means, such as a parameter. etc.
Consider Paul's rocket mass heater. |