14_static_packages - Static methods Example Java's built in...

4/27/13’1’Static revisited Static methods // Example: // Java's built in Math class public class Math { public static int abs(int a) { if (a >= 0) { return a; } else { return -a; } }public static double toDegrees(double radians) { return radians * 180 / PI; } } // Using the class: System.out.println(Math.abs(-5)); //didn’t need to create any object Static methods nstatic: Part of a class, not part of an object. nStatic methods: qDo not require an instance of the class and do not understand the implicit parameter, this; therefore, cannot access an object's instance variablesqgood for code related to a class but not to each object's stateqif public, can be called from inside or outside the class Static variables nstatic: Part of a class, rather than part of an object. qClasses can have static variables. qStatic variables are not replicated in each object; a single variable is shared by all objects of that class. private static typename;or, private static typename= value; qExample: private static int count = 0; Example nYou are writing a class to represent a bank account, and you would like the constructor to automatically assign a running number as the account number. nHow can static variables help you? Assigning ids for BankAccount public class BankAccount { // static variable for assigning an account number // (shared among all instances of the class) private static int lastAssignedNumber = 1000;

This
preview
has intentionally blurred sections.
Sign up to view the full version.