• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

When to create an object?

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have question when to create an object.
Examples:
when we use the Math methods, we write Math.random(), Math.pow()

So why we need to create an instance when we use the Scanner methods


How do I know when to create an instance or not?

Thanks in advance
 
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to look into the details of static and instance methods.

The static methods belong to the class, and therefore do not require an instance of the class to exist in order to invoke them. All the methods in the java.lang.Math class are static.

On the other hand, instance methods belong to a particular instance of the class and you require a instance of it to invoke them. That is the case of the Scanner class you mentioned above.
[ March 17, 2007: Message edited by: Edwin Dalorzo ]
 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static methods (Math.random()) can be access without creating an instance of the object. To access the public methods you need to create an instance of the class.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


To access the public methods you need to create an instance of the class.



I am affraid this is not true. The methods in question in the java.lang.Math class are public, however, since they are static, they do not require an instance of the java.lang.Math class to use them.
[ March 17, 2007: Message edited by: Edwin Dalorzo ]
 
Jing Liang
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic