This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inner question

 
Andrew Parker
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Inner class question:
Q.1 Given:
public class MyClass {
public class MyRunnable implements Runnable
{
public static void main(String [] args)
{
(new Thread(new MyRunner())).start();
}
}
How to rectify it? change it to (new Thread(new MyClass().new MyRunner())).start(); ??
Thanks
Andrew
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andrew
A couple of points.
What is the actual question you're asking?
You can't have a static method in a non-static inner class, so you'll have to move your main method to the enclosing class.
To create an instance of the inner class you need to an instacne of the enclosing class first.
This code should do what you'r elooking for:

hope that helps

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
 
Andrew Parker
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry,
I missed the void run() method and they should be separated.
Here is what I ask:
public class MyClass
{
public static void main(String [] args)
{
//MyClass.MyRunnable mr = new MyClass().new MyRunnable();
//new Thread(mr).start();
(new Thread(new MyClass().new MyRunnable())).start(); //I want to know whether they are the same.
}
public class MyRunnable implements Runnable
{
public void run(){}
}
}
Thanks for your kind help.

Andrew
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andrew
Yes both ways you have shown will accomplish the same thing - they both create and start a MyRunnable object. The major difference is that in the first way you'll actually have a reference to a MyRunnable object that you can refer to later in your code. The second way you wont.
hope that helps
------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
 
Andrew Parker
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, Dave.
I got it.
Regards
Andrew
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic