Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner Class in Java

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.

like image 782
Ashish Pani Avatar asked Dec 23 '16 15:12

Ashish Pani


People also ask

What is an inner class in Java?

In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented so bringing it closer to the real world.

Why inner classes are used in Java?

Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.

What are types of inner classes?

There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes. A class created within class and outside method. A class created for implementing an interface or extending class.

What is inner and outer class in Java?

Java inner class is defined inside the body of another class. Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access. Java Nested classes are divided into two types.


2 Answers

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

like image 164
code Avatar answered Oct 10 '22 00:10

code


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);
}
like image 22
isprout Avatar answered Oct 09 '22 23:10

isprout