9

I was reading about Inner class in Learning Java. I found this code

class Animal{
   class Brain{
   }
}

After compiling, javap 'Animal$Brain' gives output as

Compiled from "Animal.java"class 
Animal$Brain {
    final Animal this$0;
    Animal$Brain(Animal);
}

which explains how the inner class gets the reference to its enclosing instance in the inner class constructor. But when I define the inner class as private like this

class Animal{
   private class Brain{
   }
}

then after compiling, javap 'Animal$Brain' gives the output as

Compiled from "Animal.java"
class Animal$Brain {
    final Animal this$0;
}

So why is the output different? Why is the inner class constructor not shown? In the latter case also, the inner class is getting the reference of enclosing class instance.

Ashish Pani
  • 933
  • 1
  • 12
  • 19
  • 1
    I'd guess it's because the public constructor of the class is gone (you can't do `new Animal().new Brain();` now externally). – Rogue Dec 23 '16 at 17:09

2 Answers2

9

Good question. According to this,

If no options are used, javap prints out the package, protected, and public fields and methods of the classes passed to it

Since you have declared Brain as a private inner class, its default constructor will be implicitly made private and hence it will not be visible outside the Animal class.

Ref: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9

Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
code
  • 2,283
  • 2
  • 19
  • 27
  • Since javap prints the default, protected, and public fields and methods of the classes passed to it and it does not print the inner class constructor, so it implies that inner class constructor is private. – Ashish Pani Dec 23 '16 at 16:00
3

By default, javap prints non private members of the classes.

You can use -p option to shows all classes and members.

//javap -p 'Animal$Brain.class'

Compiled from "Animal.java"
class Animal$Brain {
  final Animal this$0;
  private Animal$Brain(Animal);
}
isprout
  • 31
  • 3