• Post Reply Bookmark Topic Watch Topic
  • New Topic

k&b master exam doubt  RSS feed

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class MyThread extends Thread{
public static void main(String [] args){
MyThread t = new MyThread();
t.run();
}
public void run(){
for(int i=1;i<3;i++){
System.out.print(i+"..");
}
}
}

The answer to this ques is given as 1..2..

My doubt is run()is not a static method...so how can it be accessed through the static main()? Can somebody explain ?

Thanks
 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can call non static method from static method by (objectRef).(Method name). Here you are making instance of MyThread and then calling run on that instance.
You can't call non static method from static method directly.
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You access run() through Thread object "t" so its legal, and this is the way you access non static members within static context.
 
Ranch Hand
Posts: 274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We cannot access non static methods directly, but when access through an object reference it is legal.
 
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Nisha,

Any simple Java Programs can explain this.



How you invoke an object of the class inside main() method - which is definitely static, and then call any of the instance methods of that class using the newly created object! - same holds here too!

HtH!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!