Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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!!
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!