Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Static methods are methods that belong to an entire class, not a specific object of the class. Static methods are called using the class name and the . operator.
- Eg: Math.random() in which we need not create an object in order to use the method.
- String.valueOf("2.5") -- turn that String into a double
- YourClassName.main() -- main method is also static!
- Integer.toString(1) -- turn Integer into String
- Points to note:
- Static methods and variables are associated with the class as a whole, not objects of the class.
- Static methods and variables are declared as static by using the static keyword upon declaration.
- Static methods cannot interact with non-static instance variables. This is due to static methods not having a this reference.
- Both static methods and non-static methods can interact with static variables.
- */
- public class ATM{
- // Step 2: Create your static variables here
- public static int totalMoney = 0;
- public static int numATMs = 0;
- // Instance variables
- public int money;
- // constructor
- public ATM(int inputMoney){
- this.money = inputMoney;
- }
- public void withdrawMoney(int amountToWithdraw){
- if(amountToWithdraw <= this.money){
- this.money -= amountToWithdraw;
- }
- }
- public static void main(String[] args){
- // Step 1: Create your two ATMs here
- ATM firstATM = new ATM(1000);
- ATM secondATM = new ATM(500);
- // Step 3: Print your static variable in three different ways here
- System.out.println(ATM.totalMoney); // normally access static variables thru class name
- System.out.println(firstATM.totalMoney); // can also use objects to access static variables as the value will always be the same
- System.out.println(secondATM.totalMoney);
- }
- }
Add Comment
Please, Sign In to add comment