Inner Class
An inner class is a class declared within another class. An inner class is available only from within the class it is declared.
No special syntax is required to declare an inner class. Just declare the inner class within the body of another class. Here’s an example:
public class DiceGame
{
public static void main(String[] args)
{
Dice d = new Dice();
d.roll();
}
class Dice
{
public void roll()
{
// code that rolls the dice goes here
}
}
}
In this example, the Dice
class is an inner class defined within the DiceGame
class. As a result, the Main
method within the DiceGame
class can create and use a variable of type Dice
.
Get Java For Dummies Quick Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.