nova palavra-chave é usada para criar um objeto sem atribuir a uma referência de objeto
Atualmente estou me referindo a classe Thread em java. Então, me deparei com um programa no qual o objeto é criado sem se referir ao objeto reference.can alguém pode explicar o conceito
aqui está o código
// Create a second thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
Programa principal
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
aqui new é usado para criar encadeamentos sem referência a qualquer referência de objeto. não deve ser o código como
NewThread ob = novo NewThread (); em vez de apenas new NewThread (); no método principal