Results 1 to 17 of 17
Thread: What are statics?
- 11-19-2008, 05:49 PM #1
What are statics?
I have some time to kill and I'm curious as to how statics work. I remember in one of the quiz questions there was something like
Maybe I'm not google-ing the correct term but whenever I search for static methods in java(or similar) I just get things like a static subroutine cannot use the this operator while non static subroutines can create new instances of the class. I already knew about that and was more looking towards the example of statics being called at compile time.Java Code:class mainClass{ public method1(){ } } static someStaticClass(){ //this method gets called at compile time first? }
- 11-20-2008, 04:24 AM #2
A static function is one that you can call globally, without an instance. There are also static classes, but you should not use them.
Consider a Student class. You can do things like:
The "assignGrade" is an instance function, you apply it to an instance of Student.Java Code:Student oneOfThem = new Student(); oneOfThem.assignGrade("c");
Now consider
You are calling the "getInstance" function without having an instance.Java Code:Calendar rightNow = Calendar.getInstance();
So the getInstance function is declared "static"
- 11-20-2008, 03:57 PM #3
Sorry I wasn't clear enough. I meant static initializers(just didn't know what they were called)
I get that their used for defining variables at compile time instead of run time and that they get called before any other method. There has to be something more to it though, isn't there? Whats wrong with declaring your variables inside the class or right when you need to use them? Why go through the extra hassle of figuring out every variable needed and then creating an initializer for them?
- 11-20-2008, 05:44 PM #4
static
Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
- 11-20-2008, 06:00 PM #5
Ok, so lets add a counter in the Clyde class. An instance counter would keep track of each type Clyde was used? So static initializers could be used as a form of security making sure only a set amount of that object are created or help with memory by clearing the cache or something after a certain number of initializes?
- 11-21-2008, 12:16 AM #6
Member
- Join Date
- Nov 2008
- Posts
- 14
- Rep Power
- 0
According to my knowledge the method or variable which is declared static is shared among all the objects.If any changes done by one object to the static variable or method will get effected to all the objects.
If i said anything worng please let me know.
- 11-21-2008, 08:34 AM #7
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
- 11-21-2008, 04:43 PM #8
Ok that's actually really useful information. So instead of having to set say each objects ownerID upon creation I can have a static initializer that sets it in the beginning and it won't need to be defined each time.
Thanks a lot guys for the information. I'm pretty sure I get how and when to use them now.
- 11-21-2008, 05:44 PM #9
I was reading about Enums and this line jumped out at me "You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time" (taken from Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects))
Would having an enum accomplish the same thing as having a static initialiazer?
The example they use is
Would it be more/less/null effective to do something along the lines ofJava Code:public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } private double mass() { return mass; } private double radius() { return radius; } // universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; double surfaceGravity() { return G * mass / (radius * radius); } double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } public static void main(String[] args) { double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); } }
Java Code:public enum Planet { Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } private double mass() { return mass; } private double radius() { return radius; } double surfaceGravity() { return G * mass / (radius * radius); } double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } public static void main(String[] args) { double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); } } static{ MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); final double G = 6.67300E-11; private final double mass; // in kilograms private final double radius; // in meters }
- 11-22-2008, 10:22 AM #10
instance counter
Not necessarily null or ineffective, but putting a this pointer in an enum - let's say for the moment that we would normally see that in beginner. To say the least, it either should not work or bring howls of laughter from Copernican heliocentrism - Think of an enum as something like a static final that maps strings to a numeric value, with 1,2,3,4,5... and so on being the defaults. I abandoned enums early due to their placment in the compiled work being used in another api in a manner that reeked of intrusion portal. In fact the behaviour of the entire system switched on what was put in the enum .... some appealing avenues of study are available, dig through H2 to find a rather nifty issue that is a candidate for study on one of those nights when you cannot sleep and are not really focused and want to spend a minimum of four or five hours on unguided exploratory study.
The one thing I have thought of for the moment that makes sense is the potential for a workaround for the compiler error that results from trying to init a static final in the constructor. If it would work, we could do static final current system time static{ time = System currentTimeMillis();} then do epoch's in the constructor. An instance counter is done like this:variant spellings of variable names, if any, are an adjunct to efficient time disposition while coding and are not intended to invite critical review.Java Code:/* * I waste too much time trying to write comments other people can understand. * Correct source code is self documenting. Inverse logic. */ public class LogonShell { long FinshTime; float TotalTime; String userName;// String suppliedName; StringBuffer sb;// private boolean defaultIdentity; Integer HASHCODE;long StartTime; public volatile boolean isValid; private transient boolean commonName; public volatile boolean shortLogonName; CommonPasswords cOMMONpASSWORDS = new CommonPasswords();// static String newline = System.getProperty("line.separator"); private transient int defaultUserHashCode = -1085510111;// "Default".hashCode() // int[] digraphs = {-8,9,-15,18,-8,-14,10,-6,3,-1,14,-7,6};// tech override, app enters controlled state // Shoud be replaced with pool ntp server static long seedTimeLong;// static{seedTimeLong = java.lang.System.currentTimeMillis();} // java.security.SecureRandom random; // Hey, let's add a TreeMap - the're always handy. java.util.TreeMap tm = new java.util.TreeMap(); // .........
To replacewith ++seedTimeLong resuts in what amounts to an instance counter. We could then do Interger whichOneIsThis = new Integer(seedTimeLong);// in the constructor resulting in an efficient implementation of what amounts to each whatchamacallit knowing which whatchamacallit it is, .... sort of an identity. Which raises an interesting design issue: What if we could make static initializer blocks synchronized?... wow, that would be handy!Java Code:static{seedTimeLong = java.lang.System.currentTimeMillis();}
{ message edit: see: recompile in advanced }
What's the latest on GRB 080319B ...?Last edited by Nicholas Jordan; 11-23-2008 at 02:04 AM. Reason: additional information
Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
- 11-24-2008, 06:22 PM #11
Just from the little I've read about synchronization and static initializers I'm under the impression that this wouldn't be possible unless you were running multiple threads synchronized with each other. I'm understanding that SI's are implemented in a stack order(first in first out) sorta fashion and having anything else would be against the whole concept, correct? Each thread/initializer would be unaware of the other ones but all running at the same time accomplishing multiple tasks as if it was one big initializer?
Am I correct in thinking this or has your post Nicholas, once again, confused the hell out of me and I completely missed the boat on what you were talking about.
- 11-25-2008, 12:38 PM #12
excellent work.
Actually, this is excellent work, you moved ahead of me - and in total understanding of what my post was all about. SI == Static Initializers == static{} Correct? IOW I have not seen the abbreviation SI
What you are thinking here would seem to be conceptually correct. The issue that clouds the matter is that an implementation of a jvm is at the mercy of compiler science and the person who wrote the jvm. The Java Virtual Machine is a specification, a description of a machine. With all the compiler switches and freedom left to the compiler writer, I would think that the words that I have heard that the classes are loaded ( in order ? ) and static init blocks are run before the constructor is run ~ so it makes sense. But what if we have a class LeftHandBoogie:that loads when the ui gets a button event? Then the static initializer may run whe the class is loaded and is the conceptual equivalent of initalizing the stack frame pointer so there should be only one per program. That would be of course unless the jvm runs the static initalizers for all classes that may be needed, iow the zero page AVL tree ( a self-balancing binary search tree that pages L2 ) may bring in the code, but does it branch and run the code before main is called, for all classes that may possibly be used.Java Code:stopGoButton = new JButton("Boogie Down");
Basically, you moved ahead of me and illustrated someting to me I had not thought of but what if two threads load the same class?....
Now what happens.
Thus, the basis of my question.Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
- 11-25-2008, 04:15 PM #13
Having each class generate an internal instance counter that would allow each thread to see if the class had already been loaded would stop multiple loads from happening. (Assuming 2 threads don't reach the same class in such a time difference that the instance counter isn't incremented before the second thread loads it again)
As for how the JVM builds the tree I'd assume it was designed to load each class that may be used to check for inconsistencies(some code within that program that loads a class already loaded) and overall program stability. Sacrifice some time and memory when you run the program instead of only loading a class when it's used and running the issue or a massive load time or not having enough memory to store it.
- 11-25-2008, 11:44 PM #14
( cannot see all of reply - bump )
Why and how stop other classes from loading?Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
- 11-26-2008, 12:07 AM #15
Load times
If there is only one,... wow ~ this is getting interesting. Suffice it for now, it is known that without various tools - such a static load would run indeterminate, though each thread would only increment a counter:
There still is no way to ++instanceCounter and read in without synchronization barriers. A static is, by definition, on the activation record ( stack ) thus doing ++instanceCounter would have each thread incrementing instanceCounter but what if in the constructor of BoogieBubba we do BoogieBubba(){if(instanceCounter > 99){print("get more beer");}Though only one thread can count the beers, the construcor would run at an indeterminate time clocking against static constructor..Java Code:static int instanceCounter = 0x0000;// static{++instanceCounter;}
I did some work on load times, I think we as computer scientists have some sobering realizations awaiting in the comercial realm. I fiddled with load code and got the same millisecond count no matter what I did.
I know for a fact, beyond the shadow of L-3 that what happens in commercial work is only similar to what happens in formal studies, often mechaincs of a machine are not what a student thinks they are.
I do know that load times do not need to be what they are, we often have bloated code-wagons because people insist on machines running slowly, I did an overnight test recently generating AES keys, the machine runs much faster than I thought when the code is realistic. I had previously coded for some absurd key length, then dismissed init() times as an inevitable consequence of people.
There was also another instace where I posted in a discussion asking about failure modes of Threads ~ I was so acclimatized to consumer-grade equipment runnning crappy that I went into the post on the assumption that trying to run two threads would break the machine
I had to crawl back to reality.
( folks: L-3 is Lagrange points == astronomy, nothing to do with L-2 )
{ Hint: If you want to skip ahead on this, study "static factory method" }Last edited by Nicholas Jordan; 11-26-2008 at 12:40 AM. Reason: hint
Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
- 11-27-2008, 10:36 AM #16
Member
- Join Date
- Nov 2008
- Posts
- 1
- Rep Power
- 0
static means to assceess this methos any where no need to use the create the object.Thatswhy for Main method no need to create the object
- 11-27-2008, 04:52 PM #17
static factory methods
Yes, but original poster arrived at:
which brings up fine point between static{} vWhy go through the extra hassle of figuring out every variable needed and then creating an initializer for them?which can bring up subtle timing issues. We can advance that to:Java Code:public static getInstance(){}andJava Code:public static synchronized getInstance(){};//which extracts utility from the static facility that can be OO in the sense that it coagulates various constructor designs, allowing switching on the paramater in one place rather than having to re-write several constructors.Java Code:public static synchronized getInstance(int parameter){};//Introduction to Programming Using Java.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks