Re: Static Fields Confusion
A static var (attribute) in Java is a value shared by all instances. if you change it form an instance of the class it'll change for all other instances also.
A static var (within a method) value is preserved after exiting the method unlike regular vars
Re: Static Fields Confusion
So if I instantiate a class called Book three times and I have a static variable called bookISBN and I change the value of that variables through a method, that value will then change for all three instances right? And static variables within a method would basically be just like constants right?
So then a static method would be a method shared by all instances of that class right?
Re: Static Fields Confusion
Right except that a static value in a method can be modified but doesn't lose value upon exiting method
Re: Static Fields Confusion
In OOP terms a static member or method does not require an instance of that object. To draw a real world comparison; think of a plastic mould used to create chocolate Santa's. This mould is the class/template used to create many instances of Chocolate Santa's.
On the mould however, there is a batch number. Every time you create new Santa, the batch number appears on the bottom and it does not change, however one can still read the batch number without actually creating the Santa, simply by looking at it.
In OOP terms you can access a static member or method using the class name:
Code:
class ChocolateSanta
{
private static int BATCH_NUMBER=1234;
private static int productionCount = 0;
private boolean melted = false;
public ChocolateSanta() {
productionCount++;
}
public int static getBatchNumber() {
return BATCH_NUMBER;
}
public static int getProductionCount() {
return productionCount;
}
public void melt()
{
melted = true;
}
public boolean getMelted()
{
return melted;
}
}
public class StantaFactory
{
public static void main(String[] args)
{
System.out.println(ChocolateSanta.getProductionCount() + " Santa's made");
ChocolateSanta yumYum = new ChocolateSanta;
System.out.println(ChocolateSanta.getProductionCount() + " Santa's made");
yumYum.melt();
if (yumYum.getmelted()) {
System.out.println("Sorry your chocolate santa has melted");
}
}
}
You can see that another static variable is used to keep track of the production count. And, static methods are used to access the static variables. Remember that one can only access static class variables and methods inside a static method.
You can also declare an entire class static. If you do this, you can never create an instance of it. This can be useful in a situation where you may want to create a library of global methods for example.
Re: Static Fields Confusion
You do know Santa is a myth, don't you?
Re: Static Fields Confusion
Quote:
Originally Posted by ComputerJy
You do know Santa is a myth, don't you?
Santa, is that you?