Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have multiple run methods in a class?

Tags:

java

If so, how? I need to have 2 run methods in each object I will instantiate.

I meant a run method for threading.

What i need is more like a race of two cars. each car should have a name and a run() method in a class which extends Thread. I will have to call on the two cars in my main to see which will win. The first or the second. I need help in starting my program

like image 351
Stella Kim Avatar asked Sep 27 '11 12:09

Stella Kim


People also ask

How to create multiple run methods in a single class in Java?

Thread t2 = new Thread (new Runnable () {public void run () {....}}) t1.start (); t2.start (); By using inner class you can achieve multiple run methods in a single class.

Can you have two run () methods in a thread?

You can't have two run () methods, because you (and the compiler) could not know which one to execute when calling obj.run (). Show activity on this post. Thread t1 = new Thread (new Runnable () {public void run () {...}}) Thread t2 = new Thread (new Runnable () {public void run () {....}}) t1.start (); t2.start ();

Can We define multiple methods in a class with same name?

Yes, we can define multiple methods in a class with the same name but with different types of parameters. Which method is to get invoked will depend upon the parameters passed. In the below example, we have defined three display methods with the same name but with different parameters.

Is it possible to call run () multiple times in a thread?

It's possible only to invoke another run method, with a different signature as run (String s), in the main run () method of thread.


2 Answers

A class can't contain two methods with the same signature. The signature of a method is its name followed by its arguments.

You may thus have run(int) and run(String) and run() in the same class. This is called method overloading. You can't have two run() methods, because you (and the compiler) could not know which one to execute when calling obj.run().

like image 110
JB Nizet Avatar answered Oct 11 '22 12:10

JB Nizet


Thread t1 = new Thread(new Runnable(){public void run(){...}})
Thread t2 = new Thread(new Runnable(){public void run(){....}})
t1.start();
t2.start();

By using inner class you can achieve multiple run methods in a single class.

like image 25
Aslam anwer Avatar answered Oct 11 '22 10:10

Aslam anwer