aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes cannot access non static variables from within a static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "cannot access non static variables from within a static method" Watch "cannot access non static variables from within a static method" New topic
Author

cannot access non static variables from within a static method

Netty poestel
Ranch Hand

Joined: Sep 20, 2004
Posts: 131
two examples:-

class Base {
public int iNoEnc=77;
}
public class NoEnc{
public static void main(String argv[]){
Base b = new Base();
b.iNoEnc=2;
System.out.println(b.iNoEnc);
}}
//here nonstatic iNoEnc is accesed from within static method
_________________
public class St{
int i;
public static void main(String argv[]){
i = i + 2;//Will cause compile time error
}}

so can I say, that with a '.' reference one can access non static var. from static methods ?
Thx.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Answering this question properly (even if I could) would probably mean writin a very long answer. Somebody has aleady done that: in the Java Tutorial


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Thomas Drew
Ranch Hand

Joined: Sep 15, 2004
Posts: 47
First Example should look like this. You have to assign values in the constuctor. You failed to create a constructor so the system used it's default constuctor which does nothing. You also have an extra bracket in your source code.
public class Base {

/** Creates a new instance of Base */
public int iNoEnc;
public Base() {
iNoEnc=77;

}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Base b = new Base();
b.iNoEnc=2;
System.out.println(b.iNoEnc);


}

}

Second Example
you failed to create an instance of the St Class before using it.

public class St {


int i;
public static void main(String argv[]){
St foo = new St();
foo.i+=2;
System.out.println(foo.i);
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: cannot access non static variables from within a static method