Java Static VS Instance

Java Static vs Instance

1. An instance variable is one per Object, every object has its own copy of instance variable.

Eg:

public class Test{

int x = 5;

}

Test t1 = new Test();
Test t2 = new Test();

Both t1 and t2 will have its own copy of x.

2. A static variable is one per Class, every object of that class shares the same Static variable.

Eg:

public class Test{

public static int x = 5;

}

Test t1 = new Test();
Test t2 = new Test();

Both t1 and t2 will have the exactly one x to share between them.

3. A static variable is initialized when the JVM loads the class.

4. A static method cannot access Non-static variable or method.

5. Static methods along with Static variables can mimic a Singleton Pattern, but IT'S NOT THE RIGHT WAY, as in when there are lots of classes, then we can't be sure about the class loading order of JVM, and this may create a problem.

Difference between Static methods and Instance methods

The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.

However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.

You can do this to execute a static method:

MyClass.staticMethod();  // Simply refers to the class's static code

But to execute a non-static method, you must do this:

MyClass obj = new MyClass();  //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code

On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.

Performance difference between static and instance variables

It's not a matter of performance. static and instance variables have a different purpose.

Using

int i = new MyInstatnceClass().getMyNonStaticInt();

is almost certainly useless, since each time you call new MyInstatnceClass() you create a new MyInstatnceClass instance, having a new myNonStaticInt instance variable. Since you are not keep a reference to the created instance, you cannot retrieve the same instance variable twice, which makes it useless.

If you need a single copy of a variable to be shared across all instances of the class, static variable is the way to go.

That said, the latter call is also more expansive, since it involves creation and initialization of an instance of your MyInstatnceClass class (in addition to loading and initialzing the class if it's the first access that class).

On the other hand, MyStaticClass.getMyStaticInt() only loads and initializes the class MyStaticClass if it's the first access of that class. It doesn't have to create any instance of that class.

Static vs Instance Variables: Difference?

In the context of class attributes, static has a different meaning. If you have a field like:

private static int sharedAttribute;

then, each and every instance of the class will share the same variable, so that if you change it in one instance, the change will reflect in all instances, created either before or after the change.

Thus said, you might understand that this is bad in many cases, because it can easiy turn into an undesired side-effect: changing object a also affects b and you might end up wondering why b changed with no apparent reasons. Anyway, there are cases where this behaviour is absolutely desirable:

  1. class constants: since they are const, having all the classes access the same value will do no harm, because no one can change that. They can save memory too, if you have a lot of instances of that class. Not sure about concurrent access, though.
  2. variables that are intended to be shared, such as reference counters &co.

static vars are instantiated before your program starts, so if you have too many of them, you could slow down startup.

A static method can only access static attributes, but think twice before trying this.

Rule of thumb: don't use static, unless it is necessary and you know what you are doing or you are declaring a class constant.

What is the difference between an instance and a class (static) variable in Java

A static variable is shared by all instances of the class, while an instance variable is unique to each instance of the class.

A static variable's memory is allocated at compile time, they are loaded at load time and initialized at class initialization time. In the case of an instance variable all of the above is done at run time.

Here's a helpful example:

An instance variable is one per object: every object has its own copy of its instance variable.

public class Test{

int x = 5;

}

Test t1 = new Test();
Test t2 = new Test();

Both t1 and t2 will have their own copy of x.

A static variable is one per class: every object of that class shares the same static variable.

public class Test{

public static int x = 5;

}

Test t1 = new Test();
Test t2 = new Test();

Both t1 and t2 will share the same x.

Decision of Static methods vs instance methods in java?

It's likely the answer is yes: if you have an instance method that doesn't actually take advantage of the instance state, then it should probably be static, and possibly moved to a helper class depending on what it does.

Note that even if you don't access instance variables, accessing instance methods will also disqualify a method from becoming static. Also, if this method is an instance method in order to future-proof it (in anticipation of using the instance state later,) then changing it wouldn't be advisable either.

Also important is that public non-static methods could be inherited and overriden by a subclass, so making them static could actually break the code in possibly unexpected ways.

Should I be using static or instance methods?

For starters, the difference between static and instance variables is that, only ONE static variable exists for all the instances of the class, whereas an instance variable exists for EVERY instance of the class.

Now, when you are talking about methods, in most cases you need to make a method static when you are trying to call it from another static method (such as main).

In general this practice is wrong for OOP, and chances are you should rethink the way the program is structured.

If you could provide more details about the code you use to call these methods, I would be able to help you with more details on how to fix this.

EDIT:
In light of the new info you provided:

1) I believe that bmrMain,BMRMain and Calculations can all be merged into one class. The constructor of the new class should be adjusted to read input (as well as getters and setters for each variable for added flexibility - optional)

2) Regarding the calculation of the bmr part, there are many ways to tackle this, so I will go ahead and suggest the one that is best in my opinion.
Add a Button with a text "Click to calculate" or something similar, and implement an ActionListener. The action Listener will in turn call (whenever the button is clicked) the method that calculates everything, and finally it will change the text on the JLabel.

sample code for the action Listener:

JButton button = new JButton("Text Button");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Call the methods for the calculation
// bmr and tdee are temporary variables to store the results from the methods
//handle them properly, or remove them if not needed (I just wrote a sample)
int bmr = calcBMR(...); //pass the correct variables as arguments here
int tdee;
if(userHasPickedTDEE) { tdee = calcTDEE(...); } //and here
label.setText(....);

}
});

These 2 steps will take care of your "static" problem.

I recommend that you do some research on event-driven programming

And here is some extra and more in-depth reading on Action Listeners

If you need further help, or clarifications let me know :)

EDIT2:

In general, yes it is a good practice to separate classes in order to keep the code manageable. But in this case I think it is a bit superfluous to create a new class just for 2 methods.
Nevertheless if you would like to keep the current structure, the way to fix the "static" is:
1) remove static from the 2 calculation methods.
2)line 332 should be

Calculations c = new Calculations();
bmrValue = c.calcBMR(userAge, userGender, userHeight, userWeight);

FINAL_EDIT:

Well, these questions can easily be transferred to a thread of their own. But here is a useful link from a quick google search I just did, that will help demistify the static keyword:

Static keyword in Java

Relation between class instance and static methods

Static and non-static methods/classes are entirely different beasts. Let's use an example of object-oriented programming. Say I have a class called "Person", with a constructor called Person(), with the instance variables declared as myAge (set as 0), and a method called Birthday():

int myAge;

public Person(){
myAge = 0;
}

public void Birthday(){
myAge += 1;
}

In my main method, this class would be used like this:

Person Sajjad = new Person();
Sajjad.Birthday();

When I create a new person, which is you, your age is 0, because our constructor's default values are 0 for myAge. Once I apply the Birthday() method on you, your age goes up by one, through the increment.

As for static methods, there's no object-oriented principles in it. There are uses for it.. I usually use it for simple math.

public static double addValues(double a, double b){
return a + b;
}

In my main:

int sum;
sum = addValues(1, 2);
System.out.println(sum);

Output:

3

See how above there's no need to declare a new objects? Static methods are easier to prototype, but in the long run I definitely go with object-oriented principles because it makes maintaining code in the long run so much easier. Also, I don't need to clutter my main method with unnecessary lines of code.

P.S. If the code is wrong, it's really just some pseudo code I whipped up.

Instance variable of a static nested class vs static variable of an outer class

They are different.

From a memory allocation point of view, a static inner class is no different from a top level class. Your StaticFoo will be compiled to a class (Foo$StaticFoo.class) that is essentially independent from its parent class at runtime. At compile time, there are access checks for private members.

So, in case 1, you have a static field in a class. It will be allocated as a field on a Foo.class object on the heap. There will only be one instance per ClassLoader that loads the Foo class, which generally means just one shared instance for the whole JVM.

In case 2, you have an instance field in the Foo$StaticFoo class. On the heap, there will be space allocated (and a value assigned) for (and in) each instance of StaticFoo created. Each StaticFoo that gets created will access its own instance of that field, and since it's not final, the value of each instance can be independently changed.

If you changed StaticFoo.fooInner to be static, then it would be exactly the same as case 1.

Note: The above is true only for Java 8 and later. For earlier JVMs, that amount of memory allocated in each case still matches the description above, but static variables, as well as being singletons per ClassLoader, are also stored in a different memory pool: PermGen Space rather than the main heap. See this answer for more details.



Related Topics



Leave a reply



Submit