Results 1 to 3 of 3
- 05-14-2011, 09:43 PM #1
Senior Member
- Join Date
- Feb 2009
- Posts
- 182
- Rep Power
- 5
Static and non static class methods question
Hi, I am reading a book on java , and it looks like this is true.
Static methods can be called without an object of that class being created.
such as Math.sqrt()
and Non static methods must have a Class object created to call the class methods.
such as DecimalFormat fmt = new DecimalFormat ("0.###");
fmt.format(circumference);
the "format" DecimalFormat method is not static so we need the fmt object.
My question is. Why not make all of our methods static so we never need to make an object? please. thank you. Derek
also, my book seems to create objects in 2 ways
way 1: String thisString = "this is a string object";
way 2: Random generator = new Random();
isn't String thisString a variable?
EDIT: I just posted this here. http://www.coderanch.com/t/537914/ja...ethods#2440191Last edited by silverglade; 05-14-2011 at 10:00 PM.
- 05-14-2011, 10:01 PM #2
Senior Member
- Join Date
- Nov 2010
- Posts
- 210
- Rep Power
- 3
Because that would defeat the purpose of object-oriented programming.
In your example of DecimalFormat, there's a reason that you need to instantiate the class: the instance holds all the formatting information that you give it. You could use a static method to do the same thing, but then if you wanted to use that method to do different things at different points in the program, you'd need to reconfigure it each time.
The syntax for creating strings is a special case defined by the language. If you couldn't specify string literals by using quote marks, you would have to do something like this:
which would be extremely inconvenient.Java Code:String str = new String('H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd');
thisString is a variable which holds a reference to a String object.isn't String thisString a variable?
- 05-14-2011, 10:10 PM #3
Senior Member
- Join Date
- Feb 2009
- Posts
- 182
- Rep Power
- 5
Similar Threads
-
Problems concerning Static methods and class.
By RBNSN in forum New To JavaReplies: 17Last Post: 07-15-2010, 01:11 PM -
Recursion with static and non static methods
By sh4dyPT in forum New To JavaReplies: 14Last Post: 03-27-2009, 06:56 AM -
Abstract Class with Static Methods
By bugger in forum New To JavaReplies: 7Last Post: 09-05-2008, 12:20 AM -
Newbie question about Static methods
By SCS17 in forum New To JavaReplies: 9Last Post: 02-06-2008, 08:03 AM -
Mocking static methods of class
By Kat in forum New To JavaReplies: 3Last Post: 11-08-2007, 12:24 AM


LinkBack URL
About LinkBacks
Reply With Quote
D Derek

Bookmarks