non-static variable this cannot be referenced from a static context

K

kookey

Today i always get this error:
non-static variable xxx cannot be referenced from a static context
^
e.g.
import java.net.URL;
class Test{
public static void main(String[] args){
URL url = this.getClass().getResource("1.xml");
System.out.println(url);
}
}
error: non-static variable this cannot be referenced from a static
context ^

But,when
import java.net.URL;
class Test{
public Test(){
URL url = this.getClass().getResource("1.xml");
System.out.println(url);
}
public static void main(String[] args){
Test test = new Test();
}
}
The result is right.
I want why.
 
J

Joan

kookey said:
Today i always get this error:
non-static variable xxx cannot be referenced from a static
context
^
e.g.
import java.net.URL;
class Test{
public static void main(String[] args){
URL url = this.getClass().getResource("1.xml");
System.out.println(url);
}
}
error: non-static variable this cannot be referenced from a
static
context ^

But,when
import java.net.URL;
class Test{
public Test(){
URL url = this.getClass().getResource("1.xml");
System.out.println(url);
}
public static void main(String[] args){
Test test = new Test();
}
}
The result is right.
I want why.

main() is static, Test() is not static.
 
K

kookey

why "a non-static variable cannot be referenced from a static context"
?
please say clearly , the 2nd floor - Joan.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,979
Messages
2,570,183
Members
46,719
Latest member
login dogas.info

Latest Threads

Top