1179
// update interest
double interest = BankAccount.this.balance * rate / 100;
BankAccount.this.balance += interest;
}
}
}
In the following example the InterestAdder class from the above example is declared locally within
the start method of the BankAccount class. As a local inner class InterestAdder has its scope
restricted to the method (or enclosing block) where it is declared, in this case only the start method
has access to the inner class InterestAdder, no other classes including the enclosing class has
knowledge of the inner class outside of the start method. This allows the inner class to access
private member variables of the enclosing class but only within the scope of the enclosing method
or block.
Example Language: Java (Good)
public class BankAccount {
// private member variables of BankAccount class
private String accountOwnerName;
private String accountOwnerSSN;
private int accountNumber;
private double balance;
// constructor for BankAccount class
public BankAccount(String accountOwnerName, String accountOwnerSSN,
int accountNumber, double initialBalance, int initialRate)
{
this.accountOwnerName = accountOwnerName;
this.accountOwnerSSN = accountOwnerSSN;
this.accountNumber = accountNumber;
this.balance = initialBalance;
this.start(initialRate);
}
// start method will add interest to balance every 30 days
// creates timer object and interest adding action listener object
public void start(final double rate)
{
// InterestAdder is a local inner class
// that implements the ActionListener interface
class InterestAdder implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// update interest
double interest = BankAccount.this.balance * rate / 100;
BankAccount.this.balance += interest;
}
}
ActionListener adder = new InterestAdder();
Timer t = new Timer(1000 * 3600 * 24 * 30, adder);
t.start();
}
}
A similar approach would be to use an anonymous inner class as demonstrated in the next
example. An anonymous inner class is declared without a name and creates only a single instance
of the inner class object. As in the previous example the anonymous inner class has its scope
restricted to the start method of the BankAccount class.
Example Language: Java (Good)
public class BankAccount {
// private member variables of BankAccount class
private String accountOwnerName;
private String accountOwnerSSN;
CWE Version 4.14
CWE-492: Use of Inner Class Containing Sensitive Data
CWE-492: Use of Inner Class Containing Sensitive Data