Win a copy of Hands On Software Engineering with Python this week in the Jython/Python 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

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!!
 
We can walk to school together. And we can both read this tiny ad:
Programmatically Create PDF Using Free Spire.PDF with Java
https://coderanch.com/wiki/703735/Programmatically-Create-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!