This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

last for today...the dreaded "non-static x cannot..."  RSS feed

 
Chris Pat
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
I understand that you have to creat your object before you can use them. However I cant understand why I am getting the "non-static...static method" in the code below.

Why didnt the this.framect = 0 create the object on the stack with memory for the framect and referenceable from main.

public class SimpleMP3Read {
private InputStream is;
private FileInputStream fis;
private Bitstream simple;
private int framect;

public SimpleMP3Read() {
this.framect = 0;
File test = new File("e:/devtools/src/one.mp3");
try {
InputStream fis = new FileInputStream(test); //upcasting allowed like this
}
catch (FileNotFoundException ex) {
}
Bitstream simple = new Bitstream(is);
}

public static void main(String[] args) {

SimpleMP3Read simplemp3read = new SimpleMP3Read();
try {
while (simplemp3read.simple.readFrame() != null) {
framect += 1; //nonstatic...static context without the int. with the int error on might not be initialized...it was in the constructor
}
}
catch (BitstreamException ex) {
}
}
}
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main method body is a static context, meaning that it could be invoked without the instantiation of an object. Therefore, you cannot directly access a non-static member from main -- even if an object has, in fact, been created.

I suggest that you move the try/ctach block from your main method into some instance method (see "doStuff" below), and then just call that method.
 
Jim Kiley
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Put another way, main() isn't really part of your object (it is part of the class), so it doesn't really have access to any given object's internals. If you want to manipulate the object's internal fields, you need to create one instance of the object and then ask it to manipulate its own fields.

jk
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!