---
title: "Java: Inner classes"
date: 2015-01-01
description: "## Quick summary * an inner class is a class inside of a class * inner classes are used for grouping/organization purposes * inner classes have access to their parent..."
canonical_url: https://idratherbewriting.com/java-inner-classes/
---
# Java: Inner classes
## Quick summary

 - an inner class is a class inside of a class

 - inner classes are used for grouping/organization purposes

 - inner classes have access to their parent class’s properties

At times you may want to group classes inside of classes. A class can only have one public class, but it can have other classes that aren’t public. The public class is the only class that must have the same name as the file. The only reason to create inner classes is to facilitate grouping of your logic or other content.

When you have a class inside another class, the inner class has access to the instance variables of the class it’s enclosed in.

This is an example of an inner class. We have the class Brain defined inside of the class Robot. The inner classes has access to the enclosing class’s instance variables and methods. Likewise, the enclosing class can create a new object using the inner class and then run those methods in the inner class.

```java
public class Robot {
private int id;

public Robot(int id) {
this.id = id;
}

public void start() {
System.out.println("Starting robot " + id);
Brain brain = new Brain();
brain.think();
}

class Brain {
public void think() {
System.out.println("Robot " + id + "is thinking.");

}

}
}
```