1178
return memberTwo + separator + this.innerMemberOne;
}
}
}
The only limitation with using a static inner class is that as a static member of the enclosing class
the inner class does not have a reference to instances of the enclosing class. For many situations
this may not be ideal. An alternative is to use a local inner class or an anonymous inner class as
shown in the next examples.
Example 3:
In the following example the BankAccount class contains the private member inner class
InterestAdder that adds interest to the bank account balance. The start method of the BankAccount
class creates an object of the inner class InterestAdder, the InterestAdder inner class implements
the ActionListener interface with the method actionPerformed. A Timer object created within the
start method of the BankAccount class invokes the actionPerformed method of the InterestAdder
class every 30 days to add the interest to the bank account balance based on the interest rate
passed to the start method as an input parameter. The inner class InterestAdder needs access to
the private member variable balance of the BankAccount class in order to add the interest to the
bank account balance.
However as demonstrated in the previous example, because InterestAdder is a non-static member
inner class of the BankAccount class, InterestAdder also has access to the private member
variables of the BankAccount class - including the sensitive data contained in the private member
variables for the bank account owner's name, Social Security number, and the bank account
number.
Example Language: Java (Bad)
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(double rate)
{
ActionListener adder = new InterestAdder(rate);
Timer t = new Timer(1000 * 3600 * 24 * 30, adder);
t.start();
}
// InterestAdder is an inner class of BankAccount class
// that implements the ActionListener interface
private class InterestAdder implements ActionListener
{
private double rate;
public InterestAdder(double aRate)
{
this.rate = aRate;
}
public void actionPerformed(ActionEvent event)
{
CWE Version 4.14
CWE-492: Use of Inner Class Containing Sensitive Data
CWE-492: Use of Inner Class Containing Sensitive Data