-1

This program works with no problems

public class Test{
static int DAY_IM = 1000*60*60*24;

public static void main(String[] args) {

    Calendar c = Calendar.getInstance();
    c.set(2004,0,7,15,40);
    long day1 = c.getTimeInMillis();

    for (int i  =0; i < 15 ; i++) {

        day1 += (DAY_IM *29.52);
        c.setTimeInMillis(day1);

        out.println(String.format("full moon on %tc ",c));
    }

}

I want to understand why when I move this line

 Calendar c = Calendar.getInstance();

Outside the main method, and inside the class then use reference c I can't find any method of Calendar class

I understand that Calendar class is abstract and this returns an instance of a subclass to assign to the reference, but why can't I use the reference to reach the methods outside the main method?

Tezra
  • 8,463
  • 3
  • 31
  • 68
covans
  • 41
  • 9
  • why would you want to move it outside the main method? Are there several other methods that you are not showing of the Test class? – banncee May 18 '17 at 17:47
  • For future questions: include the problematic code, not just "working code", and post the actual compiler error or runtime exception. – Mark Rotteveel May 18 '17 at 17:49

1 Answers1

1

when you move Calendar c = Calendar.getInstance(); outside the main function you're creating NON static variable in class Test

to use this variable in static method main you need to write something like this:

new Test().c.METHOD_NAME

another option is to add static to variable declaration, then you will be able to use it in main directly

Iłya Bursov
  • 23,342
  • 4
  • 33
  • 57
  • Okay but when i moved this line i also used the reference outside the main method so what the problem here ? – covans May 18 '17 at 17:53
  • @Muhammad how do you use it? – Iłya Bursov May 18 '17 at 17:54
  • Calendar c = Calendar.getInstance(); c.set(2004,0,7,15,40); imagine that there's no else code and i wanted to use only these two lines but outside the main method when i use c. as a reference i get nothing – covans May 18 '17 at 17:58
  • @Muhammad code must be within some function/method, only variable initialization are allowed – Iłya Bursov May 18 '17 at 18:01