|
Consider the following code:
public class MyThread extends Thread {
@Override
public void run(){
System.out.println("Testing thread.");
}
}
public class App
{
public static void main( String[] args )
{
MyThread thread = new Thread();
}
}
Why does the syntax checker not accept line 5 in 'App.java' (The one with the MyThread Reference Type)? If MyThread is aThread, then why is it incorrect to create a new Thread out of it? I know I'm supposed to replace it with new MyThread, but why is Thread not allowed? Doesn't 'extend' mean 'inherits all properties etc.'?
|
|
|
|
|
CsTreval wrote: If MyThread is aThread, then why is it incorrect to create a new Thread
out of it?
Your code is stating that 'Thread' is a 'MyThread' which it isn't.
The correct code would be..
Thread thread = new MyThread();
|
|
|
|
|
You should be creating the same type as you have declared thus:
MyThread thread = new MyThread();
One of these days I'm going to think of a really clever signature.
|
|
|
|
|
Yes, but there is also polymorphism as jschell said: Thread thread = new MyThread. I just got the assignment backwards. To me it is more logical to think of a=b instead b=a.
|
|
|
|
|
Thread thread = new MyThread();
...works, cause Thread is the parental to MyThread .
Using that leaves you with the basic functionality that is given in Thread (unless you cast Thread to a MyThread, then you'll be able to access the additional functions).
You could add additional functionality to any Object when you extend it - which is the basic meaning of extension.
So when initializing the Object you will have to choose the right one - the parental Object does not own the additional methods, does not know them.
You would not be able to access them.
Example:
public class Vehicle{
}
public class Bus extends Vehicle{
public int getSeatQuantity(){
}
}
A vehicle can be anything from a bike up to a race car, truck, even a train.
It's not important for a bicycle or a race car how many seats it has. But it's important for a bus.
So when you want a Bus (...and later probably know how much seats are available) you will have to create a Bus and not just a Vehicle .
Simple said: it's more specific.
|
|
|
|
|
You've got the idea now, but consider this as another way of looking at it:
a MyThread is a Thread and then some. If you had added extra class members - code or data - in the definition of MyThread , it would have stood out like the proverbial.
Another clue is in Java's use of the keyword extends .
Cheers,
Peter
Software rusts. Simon Stephenson, ca 1994. So does this signature. me, 2012
|
|
|
|
|
A super class reference variable has the capability to hold its sub class object but a sub class does not have that capability.
As MyThread is subclass of Thread, you can write
Thread t=new MyThread();
But not
MyThread m=new Thread();
That's false.
|
|
|
|