Question:
java question about Static variables?
johnny
2011-12-02 23:02:03 UTC
Hi, I got this from a java testbook problem and I'm just a little confused about static variables especially for this problem. There 4 answer. please pick 1 and kind of explain why? it would be very helpful to me. Thanks


In a ScienceExperiment class, which of the following variables would be best defined as a static variable?

1. time
2. speedOfLight
3. temperature
4. acidity
Three answers:
McFate
2011-12-02 23:07:16 UTC
speedOfLight, because it has just one value that you'd want to share across all instances of ScienceExperiment. Static variables have only one value no matter how many class instances are created.



You might have one ScienceExperiment that runs for 1 hour, and another than runs for 4 hours, so "time" would be an instance variable. Same with temperature and acidity -- those are all values that are expected to vary from ScienceExperiment to ScienceExperiment.
green meklar
2011-12-03 10:47:16 UTC
It depends what you're doing with them.



I don't like it when programming instructors (or books, or anyone for that matter) give you a bunch of variable names and ask you which ones should be declared as static, or final, or private, or whatever, as if somehow the variable name dictates how it must be used. The computer doesn't care about the variable name. And you, as the programmer, get to decide how the variable is going to be used anyway, based on your application. What do 'time', 'temperature', etc represent in the context of your application? Which ones are going to vary from one ScienceExperiment object to another? Those are the ones you leave nonstatic, the other ones you might want to declare as static. But no one can tell you without knowing what the ScienceExperiment class is actually intended to do.
hathaway
2016-10-17 08:50:20 UTC
each and every time the JVM a lot as much as run, all issues declared 'static' get thrown on the heap and initialized. If no fee is given, the default fee for the type is generated. you do no longer ought to do... public static int a = 0; static int a; // will equivalent 0 static boolean b: // will equivalent fake static double d; // will equivalent 0.0 static String s; // will equivalent "" This acts like a international. you may get admission to the time-honored public static as a class MyConstants.distanceToSun; using fact this could be a class member, no longer an merchandise. static void substantial( String[] args ) is the clarification java can in basic terms have one substantial() in any application. attempt to contain yet another class with a substantial() will bring about a RuntimeException()


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...