What Is the Exact Meaning of Static Fields in Java

What is the exact meaning of static fields in Java?

Static doesn't quite mean "shared by all instances" - it means "not related to a particular instance at all". In other words, you could get at the static field in class A without ever creating any instances.

As for running two programs within the same JVM - it really depends on exactly what you mean by "running two programs". The static field is effectively associated with the class object, which is in turn associated with a classloader. So if these two programs use separate classloader instances, you'll have two independent static variables. If they both use the same classloader, then there'll only be one so they'll see each other's changes.

As for an alternative - there are various options. One is to pass the reference to the "shared" object to the constructor of each object you create which needs it. It will then need to store that reference for later. This can be a bit of a pain and suck up a bit more memory than a static approach, but it does make for easy testability.

What's the usage of static field in Java?

static variables/methods not only have the property of being used without instantiation, but they are also consistent across multiple instances.

For example,

public class A {
public int a = 1;
public static int b = 2;
}

Now, when I do A a1 = new A() and A a2 = new A(), A.a gets 2x the memory and is stored in the object instance, while A.b gets the memory only once and is stored outside the instance.

A prime example of this would be

a1.b = 3;
System.out.println(a2.b);

This will print 3, instead of 2, because a1 changed the value of b for the whole class, and therefore, all the instances.

Static and non static fields

A static field, or static class variable within a class is accessible before an instance of that class is created unlike instance variables. Instance variables (non-static variables) within a class are created when an instance of that class is created at run-time. Hence, non-static variables cannot be accessed until an instance of that class is created. Whereas, static class members can be accessed before that class is created or instantiated.

All instances of that class can access the same static variable. On the other hand, instance variables are individual/encapsulated to each instance of a class.

Why static fields are called static?

It's a hold over from C++ and C before that. In the C context, one of its meanings was for variables that keep their value between invocations. I presume that's where 'static' comes from - it doesn't reset the value (as opposed to a const where the value cannot change)

Java use of static fields

Static fields are always class variables, which means that every instance of this class shares the same reference on this class' static fields.

In your example, it doesn't matter much BUT in the real world, your code would be useless. I think what you should have done is :

1 - define the salesTaxRate as a static field like Juned wrote

2 - define your other fields not static

3 - in your main, it would have been better to see somewhere Purchase myPur = new Purchase();

In other words (sorry for a possible mistake, i wrote the code directly here ^^) :

import java.util.*;

public class Purchase {
//Properties of Purchase class - static
private static double taxRate = 0.075; // Shared by all instances

// Members that are instance-visible
private int invoiceNumber;
private double salesAmount;
private double salesTax;

//setter for invoiceNumber, not static as it works on a non-static field
public void setInvoiceNum(int invNo){
invoiceNumber = invNo;
}

//setter for salesAmount, not static as it works on non-static fields
public void setSalesAmount(double salesAmnt){
salesAmount = salesAmnt;
salesTax = Purchase.taxRate*salesAmnt; // Note the Purchase.taxRate notation
}

//public static method to display purchase info
// I keep it static just as an example : here you HAVE to give the purchase to
// display BECAUSE the method is static
public static void displaySalesInfo(Purchase pur){
System.out.println("Invoice Number: " + pur.invoiceNumber);
System.out.println("Sales Amount: " + pur.salesAmount);
System.out.println("Sales Tax: " + pur.salesTax);
}

//main method that makes use of the static properties and display method
public static void main (String[] args) {
//ask user to input purchase details
Scanner scan = new Scanner(System.in);
System.out.println("Enter your invoice Number:" );
int inv = scan.nextInt();

System.out.println("Enter your Sales Amount:");
double sales = scan.nextDouble();

// send the user submitted purchase details to the setter methods and call display method
Purchase myPurchase = new Purchase();
myPurchase.setInvoiceNum(inv);
myPurchase.setSalesAmount(sales);
displaySalesInfo(myPurchase);
}

}

What does the 'static' keyword do in a class?

static members belong to the class instead of a specific instance.

It means that only one instance of a static field exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances.

Since static methods also do not belong to a specific instance, they can't refer to instance members. In the example given, main does not know which instance of the Hello class (and therefore which instance of the Clock class) it should refer to. static members can only refer to static members. Instance members can, of course access static members.

Side note: Of course, static members can access instance members through an object reference.

Example:

public class Example {
private static boolean staticField;
private boolean instanceField;
public static void main(String[] args) {
// a static method can access static fields
staticField = true;

// a static method can access instance fields through an object reference
Example instance = new Example();
instance.instanceField = true;
}

[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.

In laymans terms, what does 'static' mean in Java?

static means that the variable or method marked as such is available at the class level. In other words, you don't need to create an instance of the class to access it.

public class Foo {
public static void doStuff(){
// does stuff
}
}

So, instead of creating an instance of Foo and then calling doStuff like this:

Foo f = new Foo();
f.doStuff();

You just call the method directly against the class, like so:

Foo.doStuff();

What exactly does static mean when declaring global variables in Java?

Here's your example:

public class Member {

// Global Variables
int iNumVertices;
int iNumEdges;

public static void main(String[] args) {

// do stuff

iNumVertices = 0; // Cannot make a static reference to the non-static field iNumVertices

}
}

The method main is a static method associated with the class. It is not associated with an instance of Member, so it cannot access variables that are associated with an instance of Member. The solution to this is not to make those fields static. Instead, you need to create an instance of Member using the new keyword.

Here's a modified version:

public class Member {
// Fields
private int iNumVertices;
private int iNumEdges;

public Member(){
// init the class
}

public static void main(String[] args) {
Member member = new Member();
member.iNumVertices = 0;
// do more stuff
}
}

Finding yourself creating global statics is an indication to you that you should think carefully about how you're designing something. It's not always wrong, but it should tell you to think about what you're doing.



Related Topics



Leave a reply



Submit