karlakmkj

Static Methods & Variables

Aug 6th, 2021 (edited)
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. /*
  2. 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.
  3. Eg: Math.random() in which we need not create an object in order to use the method.
  4. String.valueOf("2.5") -- turn that String into a double
  5. YourClassName.main() -- main method is also static!
  6. Integer.toString(1) -- turn Integer into String
  7.  
  8. Points to note:
  9.     Static methods and variables are associated with the class as a whole, not objects of the class.
  10.     Static methods and variables are declared as static by using the static keyword upon declaration.
  11.     Static methods cannot interact with non-static instance variables. This is due to static methods not having a this reference.
  12.     Both static methods and non-static methods can interact with static variables.
  13. */
  14.  
  15. public class ATM{
  16.  
  17.   // Step 2: Create your static variables here
  18.   public static int totalMoney = 0;
  19.   public static int numATMs = 0;
  20.  
  21.   // Instance variables
  22.   public int money;
  23.  
  24.   // constructor
  25.   public ATM(int inputMoney){
  26.     this.money = inputMoney;
  27.   }
  28.  
  29.   public void withdrawMoney(int amountToWithdraw){
  30.     if(amountToWithdraw <= this.money){
  31.       this.money -= amountToWithdraw;
  32.     }
  33.   }
  34.  
  35.   public static void main(String[] args){
  36.     // Step 1: Create your two ATMs here
  37.     ATM firstATM = new ATM(1000);
  38.     ATM secondATM = new ATM(500);
  39.     // Step 3: Print your static variable in three different ways here
  40.     System.out.println(ATM.totalMoney); // normally access static variables thru class name
  41.     System.out.println(firstATM.totalMoney); // can also use objects to access static variables as the value will always be the same
  42.     System.out.println(secondATM.totalMoney);
  43.   }
  44. }
Add Comment
Please, Sign In to add comment