If I make a new Java class as follows:
class A
{
public void run() {
// do something
}
}
And then I do this:
new Thread(new A()).start()
Then I expect it to run the run() method. But it does not.
Why can’t we pass any object having the run method as an argument to new Thread()?
Why can’t java just allow any class with a run() method to run? Would there be a problem to have java implement threads in this way?
Because that’s what a language with duck typing (like JavaScript for example) would do. Java is not such a language. Two classes having the same methods are unrelated. What is important is the inhertiance relationship between their classes.
Since the
Threadconstructor accepts aRunnableas argument, only instances of classes which implements theRunnableinterface can be passed as argument.