1 Packagetimers;2 3 ImportJava.util.Timer;4 ImportJava.util.TimerTask;5 6 /*7 * Mainly want to use the object of this class in another class, how to use it? How to pass the same instance object8 */9 Public classTimerdemo {Ten Public Static voidMain (string[] args) { OneTimer T =NewTimer (); AT.schedule (NewMyTask (t), 3000); - } - } the - classMyTaskextendsTimerTask { //In order to use the T object in the main method, this instance must be passed through the constructor of the class where it is used. - PrivateTimer t; + - PublicMyTask () { + A } at - PublicMyTask (Timer t) { - This. T =T; - } - - @Override in //in this class you want to use T in the main class, and if it is created to represent another new object, it must be t in the main class so you need to pass the argument with the constructor of the class. - Public voidrun () { toSystem.out.println ("Java"); + //The object is passed through the constructor in the execution, and the object is used in this method. - T.cancel (); the * } $}
How to use objects in a running class in another class in Java, for example.