Ive trying to build some code and keep running into this error. Ive tried ways around it but it then messes with the execution of methods within Journey.
Ive looked at other threads but cant seem to find an answer.
class Main{
private Journey newJourney;
public static void main(String[] args){
startStation.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED){
String selectedItem = startStation.getSelectedItem().toString();
newJourney = new Journey();
newJourney.setStart(selectedItem);
}
}
}
);
Obviously ommited some code but thats the main just of things.
Any help is appreciated and the error im recieveing is
Main.java:102: non-static variable newJourney cannot be referenced from a static context
newJourney.setStart(selectedItem);
^
The error says it all. newJourney is not a static variable where main is a static method. This means main cannot access it. This means the following code will not work
private Journey newJourney;
you would need
private static Journey newJourney;
You should declare your object as a sataic one as following:
private static Journey newJourney;
Because you are using this object in a non-static way, It must be a static one
You may want to adopt the following paradigm, in which you create a new object for the class that your static Main method is in, and then do all your work from that object.
class Main{
private static final Main me;
private Journey newJourney;
public static void main(String[] args){
me = new Main();
me.doWork(args);
}
private void doWork(String[] args) {
startStation.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if(event.getStateChange()==ItemEvent.SELECTED){
String selectedItem = startStation.getSelectedItem().toString();
newJourney = new Journey();
newJourney.setStart(selectedItem);
}
}
}
);
}
newJourney is not static, you are trying to access into static methods.
As a Java concept, an object's state can not be changed inside static methods.
Related
public static void main(String[] args)
{
GUI TestGUI = new GUI();
TestGUI.setVisible(true);
}
public void blahh()
{
TestGUI.setVisible(true);
}
Can not find symbol for TestGUI in blahh, but can be seen in the main method.
How can I access TestGUI from other methods?
This is a scope issue. You could solve this by passing your GUI object to the blahh() method. Currently your blahh method has no way of reaching that variable.
public void blahh(GUI testGui) {
...
}
You can then call this method like this:
blahh(testGui);
Here is some reading you can do on scope, hopefully it will be helpful
Alternatively, you could declare your testGui variable as a field, and it will be accessible from anywhere in the class (make sure to make it static if you must access it in a static method). However, this will offer you less privacy with that variable even though it might seem more convenient.
because you declared TestGUI inside main method as a local varaible to a method , declare it as a class property
static GUI TestGUI;
public static void main(String[] args)
{
Test = new GUI();
TestGUI.setVisible(true);
}
public void blahh()
{
TestGUI.setVisible(true);
}
I would like to access one variable that is a part of my GUI class. Should I instantiate my GUI class outside of that GUI class? Right now it is instantiated inside of main which I believe makes it inaccessible for me.
So is the best way to access variables in this class to instantiate this object in a different class and in that class create getters and setters for it?
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
new NormalDistributionUI().setVisible(true);
}
}
Should it be like e.g.
public class Main {
static NormalDistributionUI ndUI;
public NormalDistributionUI getndUI() {
return ndUI;
}
public static void main(String args[]){
ndUI = new NormalDistributionUI();
}
}
EDIT: a different idea
public class NormalDistributionUI extends JFrame {
static NormalDistributionUI ndUI;
public static void main(String args[]) {
ndUI = new NormalDistributionUI()
ndUI.setVisible(true);
}
}
Does that make more sense than creating a separate class?
It depends on what you want. The second alternative would work as well, assuming that you called the method setVisible somewhere else.
The difference between the two of them is that in the second case the GUI object will be named and, hence, accessible afterwards. In the first case, it is anonymous.
You don't need a whole separate class. The first one is fine. If you want to manipulate the NormalDistributionUI object, you can use a local variable.
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
NormalDistributionUI ndUI = new NormalDistributionUI();
ndUI.setSomeProperty(foobar);
ndUI.setVisible(true);
}
}
I surprisingly find this confusing. I must be missing something.
So I have this simple syntax
public class OMG{
public static void main(String args[]){
int hi=2;
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt(){
hi+=1;
}
}
Obviously this cause an error, since hi is a local variable.
Judging from my experience from python I added this
public class OMG{
public static void main(String args[]){
int hi=2;
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt(){
this.hi+=1;
}
}
Which adds extra error when non-static variable cannot be accessed from a static method.
I added static to hi
public class OMG{
public static void main(String args[]){
static int hi=2;
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt(){
this.hi+=1;
}
}
The compiler scolds me for a illegal expression. I substitute the static with private (which some SO answers, recommend) but same error.
Where's my mistake? Is there any way I can solve this, without making global class?
You cannot declare static variables inside a method because static modifier means that a method or field belongs to the class.
The easiest solution to this problem would be to declare the variable as static class variable. Using this approach, you also need to remove this from this.hi in lestDoIt method. The code would be like this:
public class OMG {
static int hi=2;
public static void main(String args[]) {
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt() {
hi+=1;
}
}
Another solution may be using a non static variable hi. This would need you to also remove the static modifier to the letsDoIt method to access to hi field, because static methods cannot access to instance fields because, as explained above, static means that a method or field belongs to the class and not to a specific object instance of the class.
The solution would be:
public class OMG {
int hi=2;
public static void main(String args[]) {
//note that we have to create a new instance of OMG
//because, again, static methods cannot access to non-static methods/fields
OMG omg = new OMG();
omg.letsDoIt();
System.out.println(omg.hi);
}
public void letsDoIt() {
this.hi+=1;
}
}
More info:
Java Tutorials. Using the this Keyword
Java Tutorials. Understanding Class Members
There are two elements causing your issue.
variable hi must be referenced within a shared context between your main method and your letsDoIt method
because your main method is static, and so your letsDoIt, the will only have visibility on static fields (unless passed an instance as argument, that is)
Hence:
Declare hi as a static field of OMG:
public class OMG {
static int hi;
...
Remove the local variable declaration in your main method.
Reference it with OMG.hi or just hi within a static context, not with this.hi as this implies an instance of Main, which is not visible from a static context
You can not do "this.hi+=1" in a static context and in order to access the hi variable from "letsDoIt()" you have to declare it as a class variable like I did in the code below:
public class OMG{
public static int hi;
public static void main(String args[]){
hi=2;
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt(){
hi+=1;
}
}
Static variables are variables of the class, not its instances. You can't have a static variable inside a method.
To fix this error, move hi outside the main method (keeping it static). Also get rid of the this in letsDoIt().
public class OMG {
static int hi=2;
public static void main(String args[]){
letsDoIt();
System.out.println(hi);
}
public static void letsDoIt() {
hi+=1;
}
}
This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .
It is said that non-static variables cannot be used in a static method. But public static void main does. How is that?
No, it doesn't.
public class A {
int a = 2;
public static void main(String[] args) {
System.out.println(a); // won't compile!!
}
}
but
public class A {
static int a = 2;
public static void main(String[] args) {
System.out.println(a); // this works!
}
}
or if you instantiate A
public class A {
int a = 2;
public static void main(String[] args) {
A myA = new A();
System.out.println(myA.a); // this works too!
}
}
Also
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works too!
}
}
will work, since a is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method is static or not.
Yes, the main method may access non-static variables, but only indirectly through actual instances.
Example:
public class Main {
public static void main(String[] args) {
Example ex = new Example();
ex.variable = 5;
}
}
class Example {
public int variable;
}
What people mean when they say "non-static variables cannot be used in a static method" is that non-static members of the same class can't be directly accessed (as shown in Keppils answer for instance).
Related question:
Accessing non-static members through the main method in Java
Update:
When talking about non-static variables one implicitly means member variables. (Since local variables can't possible have a static modifier anyway.)
In the code
public class A {
public static void main(String[] args) {
int a = 2;
System.out.println(a); // this works!
}
}
you're declaring a local variable (which typically is not referred to as non-static even though it doesn't have a static modifier).
The main method does not have access to non-static members either.
final public class Demo
{
private String instanceVariable;
private static String staticVariable;
public String instanceMethod()
{
return "instance";
}
public static String staticMethod()
{
return "static";
}
public static void main(String[] args)
{
System.out.println(staticVariable); // ok
System.out.println(Demo.staticMethod()); // ok
System.out.println(new Demo().instanceMethod()); // ok
System.out.println(new Demo().instanceVariable); // ok
System.out.println(Demo.instanceMethod()); // wrong
System.out.println(instanceVariable); // wrong
}
}
This is because by default when you call a method or variable it is really accessing the this.method() or this.variable. But in the main() method or any other static method(), no "this" objects has yet been created.
In this sense, the static method is not a part of the object instance of the class that contains it. This is the idea behind utility classes.
To call any non-static method or variable in a static context, you need to first construct the object with a constructor or a factory like your would anywhere outside of the class.
More depth:
Basically it's a flaw in the design of Java IMO which allows static members (methods and fields) to be referenced as if they were instance members. This can be very confusing in code like this:
Thread newThread = new Thread(runnable);
newThread.start();
newThread.sleep(1000);
That looks like it's sending the new thread to sleep, but it actually compiles down into code like this:
Thread newThread = new Thread(runnable);
newThread.start();
Thread.sleep(1000);
because sleep is a static method which only ever makes the current thread sleep.
Indeed, the variable isn't even checked for non-nullity (any more; it used to be, I believe):
Thread t = null;
t.sleep(1000);
Some IDEs can be configured to issue a warning or error for code like this - you shouldn't do it, as it hurts readability. (This is one of the flaws which was corrected by C#...)
**Here you can see table that clear the access of static and non-static data members in static and non-static methods. **
You can create non-static references in static methods like :
static void method() {
A a = new A();
}
Same thing we do in case of public static void main(String[] args) method
public class XYZ
{
int i=0;
public static void increament()
{
i++;
}
}
public class M
{
public static void main(String[] args)
{
XYZ o1=new XYZ();
XYZ o2=new XYZ();
o1.increament();
XYZ.increament(); //system wont be able to know i belongs to which object
//as its increament method(static method)can be called using class name system
//will be confused changes belongs to which object.
}
}