Thursday, July 30, 2009

JAVA QUESTION: How are static fields and methods different from non-static fields and methods?

How are static fields and methods different from non-static fields and methods? What would go wrong if we declared the balance field of a bank account class to be static? What could go wrong if every account had a field containing today's interest rate?

JAVA QUESTION: How are static fields and methods different from non-static fields and methods?
Static fields and methods belong to the class not the individual instances of the class. All instances of a given class share the same static variables/methods.





For example:





public class Dog {


public static String breed;


public String name;


}





-----





public class StaticTest {





public static void main(String[] args) {


Dog dog1 = new Dog();


dog1.name = "Spot";


dog1.breed = "German Shepherd";





Dog dog2 = new Dog();


dog2.name = "Fido";


dog2.breed= "Mutt";





System.out.println(dog1.name + " is a " + dog1.breed);


System.out.println(dog2.name + " is a " + dog2.breed);


}


}








When run, you'll get:





Spot is a Mutt


Fido is a Mutt





Because while name belongs to each individual instance of Dog, breed is shared among all Dog's





Hopefully you can see the disastrous results of making checking account balance a static attribute. Everyone at the bank would always have the same amount of money.





On the other hand, keeping today's interest rate in each account is too much overhead since the interest rate should be shared by all customers.





Static methods also work well for functions that don't necessarily require an object to be created in order to run that function.





For example:





public static long farenheitToCelcius(int F, int C);


and


public static final String RGB_BLUE = "#0000FF";





could be called from anywhere without have to instantiate their parent objects.


No comments:

Post a Comment