Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Markus, exam 1 Q51

 
Jeff L.
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen when you compile and run the following code?
public class Scope{ private int i; public static void main(String argv[]){Scope s = new Scope();s.amethod(); }//End of main public static void amethod(){System.out.println(i); }//end of amethod}//End of class
1) A value of 0 will be printed out
2) Nothing will be printed out
3) A compile time error
4) A compile time error complaining of the scope of the variable i
-------------------->
In the official answer, 3 is preferred over 4 because:
"...Thus you will get an error saying something like
Can't make a static reference to a non static variable"
I thought that scope was defined as the set of code locations where a particular variable is usable, and static vs. non-static is one of the determiners of scope, so I would consider the official answer to support option 4 as being superior to option 3.
Is this not what scope means?
 
Ana Abrantes
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But you can only refer to a non-static member through an instance of the class.
Static is not a scope, it says that the method/variable is related to the class and not the instance, so how can you refer to an instance variable if you don't have an instance related to it?
That's the point and not scope.
It would work if you changed like this:
public class Scope{
private int i;
public static void main(String argv[]){
Scope s = new Scope();
amethod(s);
}//End of main
public static void amethod(Scope s){
System.out.println(s.i);
}//end of amethod
}//End of class
Ana
 
Ana Abrantes
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's another possible solution:
public class Scope{
private int i;
public static void main(String argv[]){
Scope s = new Scope();
System.out.println(s.i);
}//End of class
Ana
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic