Java Reference
In-Depth Information
Note that the object amount of the inner class Money is created starting with an object,
account , of the outer class BankAccount , as follows:
BankAccount.Money amount =
account. new Money("41.99");
Also, note that the syntax of the second line is not
new account.Money("41.99"); //Incorrect syntax
Within the definition of the inner class Money , an object of the inner class can
invoke a method of the outer class. However, this is not true outside of the inner class.
Outside of the inner class, an object of the inner class can only invoke methods of the
inner class. So, we could not have continued the previous sample code (which is outside
the class BankAccount and so outside the inner class Money ) with the following:
System.out.println(amount.getBalance()); //Illegal
The meaning of amount.getBalance() is clear, but it is still not allowed. If
you want something equivalent to amount.getBalance() , you should use the
corresponding object of the class BankAccount ; in this case, you would use account.
getBalance() . (Recall that account is the BankAccount object used to create the
inner class object amount .)
Now let's consider the case of a static inner class. You can create objects of a public
static inner class and do so outside of the inner class—in fact, even outside of the outer
class. To do so outside of the outer class, the situation is similar to, but not exactly the
same as, what we outlined for nonstatic inner classes. Consider the following outline:
public class OuterClass
{
public static class InnerClass
{
public void nonstaticMethod()
{ ... }
public static void staticMethod()
{...}
Other_Members_of_InnerClass
}
Other_Members_of_OuterClass
}
You can create an object of the inner class outside of the outer class as in the
following example:
OuterClass.InnerClass innerObject =
new OuterClass.InnerClass();
Search WWH ::




Custom Search