-Can be accessed at class level
public class AccountHandler {
-Does not require Class instance (aka Object)
-Static variable keeps only one value during entire program execution,
unlike Instance variable, which maintains separate values (state) per instance (Object)
unlike Instance variable, which maintains separate values (state) per instance (Object)
======================================================
Example: To demonstrate Static and Instance variables and methods
public static double MAX_DEPOSIT_LIMIT = 1000000;
//Instance method to deposit specified amount to specified customer Id
public void doDeposit(String customerId, double amount) {
if (amount > MAX_DEPOSIT_LIMIT) {
System.out.println("Can not process, exceeding limits, Amount: " + amount);
return; //return to caller
}
System.out.println("Depositing amount " + amount + " for Customer Id : " + customerId);
}
//Static method to show customer's ß for the specified customer Id
public static void showPortfolio(String customerId) {
System.out.println("Showing Portfolio for Customer Id : " + customerId);
}
}
---------------------------------------------------------------------------
---------------------------------------------------------------------------
public class TestStatic {
public static void main(String[] args) {
//check account deposit limits by accessing static MAX_DEPOSIT_LIMIT
System.out.println("Allowable deposit limit : " + AccountHandler.MAX_DEPOSIT_LIMIT);
AccountHandler handler = new AccountHandler();
//calling instance method by using dot operator on instance of AccountHandler class
handler.doDeposit("a007", 10000);
//calling static method by using dot operator on AccountHandler class
AccountHandler.showPortfolio("a007");
}
}
No comments :
Post a Comment