Search code examples
javaandroidclasschronometer

Checking Chronometer Time from Another Class Shortcut


I have a Chronometer in Class Apple. I want to check what time the Chronometer is at in Class Banana. I do not want to create a Chronometer in Class Banana, nor do I want to make an Apple Object in Class Banana. Is this possible?

Thanks!

Let me know if i can be more specific.


Solution

  • Is there more than one Apple in your (presumably) game?

    If there is exactly one then you can make the chronometer a public static member of Apple and just read it from within your instance of Banana. Like this:

    public class Banana {
    
     public void foo() {
       System.out.print(Apple.chronometer.printValue()); 
     }
    }
    

    If there are multiple Apple instances, then you need 1) put them into some sort container; 2) pass in, set, or construct your instance of Banana with a reference to that container; 3) Access the appropriate apple instance in the container, and read the chronometer's value, call its methods, etc. If the chronometer is a private member of Apple, you need to provide an accessor method so it can be accessed by code in your Banana instance.