Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java what are nested classes and what do they do?

In java what are nested classes and what do they do?

like image 763
David Avatar asked Sep 19 '25 07:09

David


2 Answers

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

like image 65
Michael Mrozek Avatar answered Sep 21 '25 22:09

Michael Mrozek


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.

like image 33
Robert Kosara Avatar answered Sep 21 '25 22:09

Robert Kosara