Continents and Cities - declaring variables outside of the main method

If I declare the variable int continent above and outside of the main method, the code cannot compile.
Can someone explain this?
I thought code declared as an instance variable has global scope so would be available to the main method?
The error displayed is as follows -
Continents.java:9: error: non-static variable continent cannot be referenced from a static context switch (continent) { ^ 1 error
The non error throwing final version of code, with int continent declared in main, is shown below.

Thank you for your help! :slight_smile:

public class Continents {
// main method
	public static void main(String[] args) {
//switch statement 
int continent = 4;
switch (continent) { 
  case 1 : 
   System.out.println("North America: Mexico City, Mexico");
    break ; 
  case 2:
    System.out.println("South America: Sao Paulo, Brazil");
    break; 
  case 3 :
    System.out.println("Europe: Moscow, Russia"); 
    break; 
  case 4:
   System.out.println("Africa: Lagos, Nigeria");
   break; 
  case 5 :
    System.out.println("Asia: Shanghai, China");
    break; 
  case 6: 
    System.out.println("Australia: Sydney, Australia");
    break;
  case 7 : 
    System.out.println("Antarctica: McMurdo Station, US");
    break;
  default: 
    System.out.println("Undefined continent!");
    break; 
	}
} 
 
}

If a variable [in a class, but outside a method] is not static, then you’d need to create a object (an instance of the class) in order to access that variable.

so this fails:

public class MyClass {
  int x = 3;
  public static void main(String[] args) {
    System.out.println(x);  // error here, can't access x
  }
}

but this will work:

public class MyClass {
  static int x = 3;
  public static void main(String[] args) {
    System.out.println(x);
  }
}

or you could make an instance of the class:

public class MyClass {
  int x = 3;
  public static void main(String[] args) {
    // create an instance (a MyClass object) called mine
    MyClass mine = new MyClass();
    // can now access x as mine.x (for that object)
    System.out.println(mine.x);
  }
}

Note that the .x could be made to be a different integer for each instance (each MyClass object).

1 Like

This is an awesome explanation. Very clear! Thank you :smiley: