Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why does this fail? I don't quite understand.

 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I understand that I get
"Can't make a static reference to a non static variable".
But I'm still not getting the gist of this.
------------------
What's this H2SO4 doing in my fridge?? ( thud )
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
main is a static method. It is a class level method and does not relate to any particular INSTANCE of the class.
However your variable MyArg is an instance variable. Each time you create a new Arg object it will have it's own MyArg. \
The static method does not know WHICH instance's MyArg you are talking about, so it complains.
To do this you need to MAKE an Arg and the use the variable for that one instance in the static method.
Arg x = new Arg();
x.MyArg=argv;
System.out.println(x.MyArg[1]);
Now it knows which one to look at.

[This message has been edited by Cindy Glass (edited May 07, 2001).]
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or, of course you could make the variable a class variable so that it also does not relate to any particular instance of the class by making it static also. Then the static method CAN access it.
PS Do your realize that the first thing in the array is at MyArg[0] not [1]?
[This message has been edited by Cindy Glass (edited May 07, 2001).]
 
Dale DeMott
Ranch Hand
Posts: 515
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes I did know that Cindy. Thank you for the reminder though Thank you for the helpful information as well.
------------------
What's this H2SO4 doing in my fridge?? ( thud )
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic