In java what are nested classes and what do they do?
They're just classes within other classes. They make it possible to have a hierarchy of classes, and if you make them private they're a convenient way to encapsulate data that isn't exposed outside of the class using them. Sun has a short tutorial about them
One of the most important uses of inner classes in Java are listeners. Instead of writing an entire separate class for an ActionListener
or similar, you create it in-place:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
... your code here ...
}
}
These inner classes typically call functions in the outer class (they capture a pointer to the object they were created in), and lead to much tidier code than having a single callback with some logic that has to figure out which button etc. was clicked. You also don't have to modify code in several places when you add or remove a button, since the inner class is created where you create the button. It's quite elegant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With