Inner Class
Definition:
An inner class is a class that is declared within another class:
public class SimpleCalc {private class OperatorAction{}}
Being able to nest classes in this way has certain advantages:
- It can hide the class from other classes - especially relevant if the class is only being used by the class it is contained within. In this case there is no need for the outside world to know about it.
- It can make code more maintainable as the classes are logically grouped together around where they are needed.
- The inner class has access to the instance variables and methods of its containing class.
Example:
A typical use of an inner class is for event listeners. You might have buttons that perform similar roles that can take advantage of the user of an inner class to implement an
ActionListener
interface:public class SimpleCalc{public SimpleCalc(){//rest of code..JButton addButton = new JButton("+");addButton.setActionCommand("+");OperatorAction subAction = new OperatorAction(1);addButton.addActionListener(subAction);JButton subButton = new JButton("-");subButton.setActionCommand("-");OperatorAction addAction = new OperatorAction(2);subButton.addActionListener(addAction);//rest of code..}private class OperatorAction implements ActionListener{private int operator;public OperatorAction(int operation){operator = operation;}public void actionPerformed(ActionEvent event){currentCalc = Integer.parseInt(numberCalc.getText()); calcOperation = operator;}}}
Note: An example of the use of implementing an
ActionListener
by using an inner class can be found in the A Simple Calculator Handling Button Events step-by-step. The full Java code listing can be found in a Simple Calculator Example Program.Glossary:
#ABCDEFGHIJKLMNOPQRSTUVWXYZ