14_static_packages

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

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
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 n static : Part of a class, not part of an object. n Static methods: q Do not require an instance of the class and do not understand the implicit parameter , this ; therefore, cannot access an object's instance variables q good for code related to a class but not to each object's state q if public , can be called from inside or outside the class Static variables n static : Part of a class, rather than part of an object. q Classes can have static variables . q Static variables are not replicated in each object; a single variable is shared by all objects of that class. private static type name ; or, private static type name = value ; q Example: private static int count = 0; Example n You 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. n How 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;
Background image of page 1

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

View Full Document Right Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 4

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

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online