1
public class game extends Thread{
    public void run() {
        System.out.println("Sub-class must override the void run() method of Thread class!");
    }
    public static void main(String args[]) {
        Thread t = new Thread();
        t.start();
    }
}

For these lines of code above I got nothing in the console. But for these codes below:

public class game extends Thread{
    public void run() {
        System.out.println("Sub-class must override the void run() method of Thread class!");
    }
    public static void main(String args[]) {
        game g = new game();
        g.start();
    }
}

I got "Sub-class must override the void run() method of Thread class!" shown in the console.

Could you help me, why I need to create an object of the sub-class rather than an object of the Thread class? What's the difference? Sorry I am a total novice.

2 Answers 2

2

If you create an instance of the parent class, the compiler will not know about its child. That is why you need to instantiate the sub class oppesed to the parent.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! I seems to get it.
2

That's because in the first code the object is a default thread that has no task to run. You could have given the thread object a task like this,

public class game implements Runnable{
    public void run() {
        System.out.println("Sub-class must override the void run() method of Thread class!");
    }
    public static void main(String args[]) {
        Thread t = new Thread(new game());
        t.start();
    }
}

Whereas in the second case you give the Thread (its Sub-class Game) a default task to print in its run method. See more about threads here

2 Comments

Sir thank you! Thread t = new Thread(game); Here what is the game inside the ()? Is it a String name or runnable r? I am confused at here for days... Thank you!
Its a Runnable, when you don't pass a Runnable to a normal Thread it does nothing. A thread is spawned to do a task, by default a thread doesn't know what task to do, unless, you give it one through runnable task (passing a Runnable on construction). Or you create your custom thread class to do something when run (by overriding the run method)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.