Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

When to create an object?

 
Jing Liang
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • 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
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • 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 ]
 
Srikanth Ramu
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Quote
  • Report post to moderator
Thank you very much
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic