简体   繁体   中英

What is the main difference between using inheritance and polymorphism to instantiate of an object of a subclass of Thread?

What is the main difference between these two following codes in multiple threading when we have a class such as AnotherThread and it extends Thread and we override run method inside it. When do we need to use polymorphism for creating an instance of AnotherThread class? And when we have to use inheritance for creating an of AnotherThread class?

This is a subclass of Thread:

public class AnotherThread extends Thread{

    @Override
    public void run() {
        System.out.println("Hello from another thread.");
    }
}

in this code why we use Polymorphism to instantiate of an object of AnotherThread class where AnotherThread is a subclass of Thread:

public static void main(String[] args) {

    System.out.println("This is the main thread.");


    Thread anotherThread = new AnotherThread();
    anotherThread.start();

And in this code why we use inheritance to instantiate of an object of AnotherThread class where AnotherThread is a subclass of Thread:

public static void main(String[] args) {

    System.out.println("This is the main thread.");

    AnotherThread anotherThread_2 = new AnotherThread();
    anotherThread_2.start();

There is no difference AT ALL in the instantiation of the thread. The only difference is in the type of the variable that holds the reference to the thread.

First question: do you understand the difference between an object and a reference to an object? A variables is not the object, it holds a reference.

So the question is, do you want your program to treat the thread as a general Thread (first example) or as AnotherThread (second example)? Both of these are valid, it just depends on what you want to accomplish. In general, if subsequent code has no need to treat it specifically as AnotherThread, then programming to the Thread interface is preferred.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM