Search code examples
javareturn

Return variable from timerClass


So i'm trying to make a speedrun clock and I dont know how to get the variable "i" in class timerClass extends TimerTask to return to my main. Any Ideas?

class timerClass extends TimerTask {   
    @Override
    public void run() {       
        System.out.println(i++);
    }
    int i = 0; 
}

Solution

  • Class cannot return a value.

    You have two options to access i from main().

    1- Use a function to return i and call that function from the main().

    2- Simply access i from main by using an object of your timerClass.

    timerClass obj = new timerClass();
    System.out.println(obj.i);
    

    Tip: if i us public, you can simply access it by using an object of your class. If i is private variable, use a function that returns i and call it from main() using an object of your class.