Reputation: 51
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.
Upvotes: 1
Views: 108
Reputation: 1329
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
Upvotes: 2
Reputation: 4443
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.
Upvotes: 2