A simple interest calculator
Consider the following implementation of an interest calculator:
-
Maven module source code available at
P/Sd1/interest/V1
.
- Instance versus class variables and methods
-
Examples:
- Instance variables and methods, non-static declaration
-
private double balance
,public void setBalance(double balance)
- Class variables and methods, static declaration
-
private static double
interestRate,public static void setInterestRate(double z)
For both categories chapter 5, “Fields in a Class Definition” and “Methods in a Class Definition”.
- Formal parameter names and variable scopes
/** * Setting the interest rate common to all accounts. * * @param z * the desired (global) interest rate. */ public static void setInterestRate(double z) { // Scope of variable "z" limited to // just the current block {...}, interestRate = z; // in contrast interestRate has } // class scope.
The formal variable's name “
z
” may be consistently renamed to any other legal, non-conflicting value like “myFunnyVariableName
”:public static void setInterestRate(double myFunnyVariableName) { interestRate = myFunnyVariableName; }
Alternatively name shadowing conflicts may be resolved by using the keyword
this
❶:public class Konto { ... private double balance;// variable "balance" being shadowed inside body of // setBalance(...) ... public void setBalance(double balance) { if (balance <= 10000) { this.balance ❶ = balance; // "this" required to resolve name shadowing // conflict by method parameter name // "double balance". } else { System.err.println("Balance" + balance + " exceeds " + 10000); } } ... }
- Access restrictions public / private / protected to attributes and methods
public class Account { private static double // Visible for class methods only interestRate = 1.5; ... public void applyInterest() { // Externally visible balance = balance * (1 + interestRate / 100); } ...
See , chapter 5, “CONTROLLING ACCESS TO CLASS MEMBERS”.
- Method overloading
-
Example:
public class Account { public Account() { // Default Constructor without any parameter setBalance(0); } ... public Account(double balance) { // Overloaded non-default constructor creating setBalance(balance); // an account with (possibly) non-zero balance. } ... public void applyInterest() { // Just one year's interest. balance = balance * (1 + interestRate / 100); } ... public void applyInterest(int years) { // Overloaded method allowing for different balance = balance * // time periods. Math.pow((1 + interestRate / 100), years); } ... }
See , chapter 5, “METHOD OVERLOADING”.
- Use of standard mathematical functions
Math.pow((1 + interestRate / 100), years)
See , chapter 2, “MATHEMATICAL FUNCTIONS AND CONSTANTS”.