| Author |
When to create an object?
|
Jing Liang
Ranch Hand
Joined: Oct 23, 2006
Posts: 40
|
|
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
Joined: Dec 31, 2004
Posts: 961
|
|
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
Joined: Feb 20, 2007
Posts: 76
|
|
|
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
Joined: Dec 31, 2004
Posts: 961
|
|
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
Joined: Oct 23, 2006
Posts: 40
|
|
Thank you very much
|
 |
 |
|
|
subject: When to create an object?
|
|
|