JVM Memory Areas and Scope - Yash-777/LearnJava GitHub Wiki


new Object() {
    public void a() {
        /*code*/
    }
}.a();

Check .class files. weather it generates anonymous inner class.

-> If you are creating inner class it generates 2.class files.

Inner Classes

An inner class is a class that is defined inside another class. Why would you want to do that? There are three reasons:

Inner class methods can access the data from the scope in which they are defined—including the data that would otherwise be private. Inner classes can be hidden from other classes in the same package. Anonymous inner classes are handy when you want to define callbacks without writing a lot of code.

Anonymous inner class

public class Gui {
    LineGraph graph = new LineGraph() {
        // extra functionality here.
    };
}

Named inner class

public class Gui {
    MyLineGraph graph = new MyLineGraph();

    private class MyLineGraph extends LineGraph {
        // extra functionality here.
    }
}

One advantage of anonymous inner classes is that no one can ever use it anywhere else