Search code examples
javamain-method

Calling a static method on an abstract class outside the main method


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?


Solution

  • 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