|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
Syntax to call a static method:
Class.methodName(args…) |
You can call the method even if no objets of that type exist. (example: Math.sqrt(25), BankAccount.getBankHQAddress())
Caveat: It makes no sense to mention “this” in a static method. Why not? Remember, “this” is a special parameter which gets initialized to “the object whose method is being called”; static methods aren't called with respect to an object (and in fact, might even be called before any objects exist), hence there is no sensible notion of “this”
We've mentioned, that if you write (say) getBalance() in the middle of a method, Java completes it to be this.getBalance(). So be aware that you might be implicitly writing “this” even if you don't type those characters.
The rule for static: If the field's value — or method's answer — is the same regardless of which object you have, it should be static.
public static final int MAX_BRIGHTNESS = 256; public static void doodad() { final int HEIGHT = 500; final int WIDTH = 600; int[][] nums = new int[HEIGHT][WIDTH]; // Initialize all 500 rows: for (int i=0; i < HEIGHT; ++i) { // Initialize row#i -- that is, nums[i][0]..nums[i][600]: for (int j=0; j < WIDTH; ++j) { nums[i][j] = (i*j*MAX_BRIGHTNESS) / (WIDTH * HEIGHT); } } Pict.displayPixels( nums ); } |
Note that every time we call displayPixels, the window has the next number in sequence. That's because there is a static field, keeping track of how many times that method has been called. Every time displayPixels is called, that static field gets incremented by one.
Let's add the same concept to BankAccount: The bank (class) itself will ahve a field accountsMadeSoFar. And: every object will have a field accountNum (should it be static?). How will we initialize that field?
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Apr.24 (Fri) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |