Java Inner Classes

An inner class is a class nested within another class. We can describe an inner class schematically as follows:

class Outer
{
class Inner
{
....
}
}


An inner class has access to member variables of the enclosing, outer, class even if they are declared private. An instance of an inner class can exist only within an instance of the enclosing class. To illustrate this, the Account class includes the Statement inner class.


Account

public class Account
{
private int accountNo;

private String accountName;
private double balance;
public Account(int accountNo, String accountName, double balance)
{
this.accountNo = accountNo;
this.accountName = accountName;
this.balance = balance;
}

public class Statement
{
private int statementNo;

public Statement(int statementNo)
{
this.statementNo = statementNo;
}

public void printStatement()
{
System.out.println(''Account No: " + accountNo);
System.out.println("Statement No: " + statementNo);
System.out.println("Balance: " + balance);
}
}
}


As before, Account has a constructor (lines 6–11). Lines 13–25 define the Statement inner class. Every Statement has a statement number, and this is initialized in the inner class constructor (lines 16–18). Statement also has a method, printStatement (lines20–24), that prints account and statement details. Note that accountNo and balance are private variables belonging to the outer, Account, class. Private variables, as we have seen, can normally be accessed only in the current class. However, inner classes are an exception, and we can access accountNo and balance in printStatement.

Note that when we compile the Account.java program, we produce two class files: Account.class and Account$Statement.class. In this way, the one-to-one relationship of class to class file is maintained.

Recall that an inner class instance can exist only within an outer class instance, so the format for creating these instances is

OuterClass OuterClassInstance = new OuterClassConstructor;
OuterClass.InnerClass InnerClassInstance =
OuterClassInstance.new InnerClassConstructor;


Consequently, the statement

Account shamsa = new Account(456, ''Shamsa", 500);

will create an Account, shamsa, as expected. The statement

Account.Statement shamsaStatement = shamsa.new Statement(7);

creates shamsaStatement, which is an instance of the inner, Statement, class with a statement number of 7. We cannot create this instance unless the outer class instance, in this case shamsa, is present. We can then invoke an inner class method in the usual way,
for example

shamsaStatement.printStatement();

Inner classes can be embedded within a method; these are known as local inner classes. It is possible to create local inner classes without a name, or anonymous inner classes.

No comments:

Post a Comment