Declaring an Inner Class
You'll learn where to place an inner class declaration inside an outer class and the basic syntax required.
What Is an Inner Class Declaration?
An inner class is a class declared inside another class, without the static keyword. Unlike static nested classes (which you just learned), inner classes are instance members—they belong to an instance of the outer class, not the class itself.
The declaration looks like a normal class declaration, but it sits inside the curly braces of the outer class, just like fields and methods do.
Basic Syntax
public class OuterClass {
// Fields and methods of outer class
// Inner class declaration
class InnerClass {
// Fields and methods of inner class
}
}
Notice the absence of static—that's what makes it an inner class rather than a static nested class.
Where to Place the Declaration
You can declare an inner class anywhere inside the outer class body:
public class Document {
private String title;
// Inner class declared after fields
class Paragraph {
private String text;
public String getText() {
return text;
}
}
// More outer class methods
public String getTitle() {
return title;
}
}
The order doesn't matter functionally, but convention typically places inner class declarations at the end of the outer class for readability.
Access Modifiers Apply
Like any class member, you can use access modifiers:
public class Bank {
private class Account { // Only visible inside Bank
// ...
}
protected class Transaction { // Visible to subclasses
// ...
}
}
Key Takeaway: An inner class is declared inside an outer class without static, making it an instance member that belongs to instances of the outer class.