Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Inner Classes

Java Inner Classes

In Java, nesting classes (placing a class within another class) is permissible. Nested classes are employed to consolidate related classes, enhancing code readability and maintainability.

To access the inner class, instantiate the outer class followed by the inner class.

Example

class OuterClass {
  int x = 10;

  class InnerClass {
    int y = 5;
  }
}

public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.y + myOuter.x);
  }
}

// Outputs 15 (5 + 10)

Private Inner Class

In contrast to a “regular” class, an inner class can be designated as private or protected. To restrict external access to the inner class, declare it as private:

Example

class OuterClass {

  int x = 10;

 

   private class InnerClass {

    int y = 5;

  }

}

 public class Main {

  public static void main(String[] args) {

    OuterClass myOuter = new OuterClass();

    OuterClass.InnerClass myInner = myOuter.new InnerClass();

    System.out.println(myInner.y + myOuter.x);

  }

}

Attempting to access a private inner class from an external class results in an error.

Main.java:13: error:  OuterClass.InnerClass  has private access in OuterClass

    OuterClass.InnerClass myInner = myOuter.new InnerClass();

              ^

Static Inner Class

An inner class can also be static, allowing access without the need to instantiate an object of the outer class.

Example

class OuterClass {
 
int x = 10;
  static class InnerClass {
    int y = 5;
  }
}
public class Main {
public
static void main(String[] args) {
    OuterClass.InnerClass myInner = new OuterClass.InnerClass();
   
System.out.println(myInner.y);
  }
}
 // Outputs 5

 

Note: just like static attributes and methods, a static inner class does not have access to members of the outer class.

Access Outer Class From Inner Class

An advantage of inner classes is their ability to access attributes and methods of the outer class:

Example

class OuterClass {
  int x = 10;
   class InnerClass {
  public int myInnerMethod() {
      return x;
    }
  }
}
 public class Main {
  public static void main(String[] args) {
    OuterClass myOuter = new OuterClass();
    OuterClass.InnerClass myInner = myOuter.new InnerClass();
    System.out.println(myInner.myInnerMethod());
  }
}
 
// Outputs 10