Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

cannot access non static variables from within a static method

 
Netty poestel
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Thomas Drew
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic