Java Inner Classes

JK JK 2018 
Created at
Updated at  
7,045 0 0

In Java, it is also possible to nest classes (a class within a class). The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.

To access the inner class, create an object of the outer class, and then create an object of the inner class:

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

Unlike a "regular" class, an inner class can be private or protected. If you don't want outside objects to access the inner class, declare the class as private:

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);
  }
}

If you try to access a private inner class from an outside class, an error occurs:

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, which means that you can access it without creating an object of the outer class:

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

Access Outer Class From Inner Class

One advantage of inner classes, is that they can access attributes and methods of the outer class:

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

 

Tags Access Outer Class From Inner Class Java Java Inner Classes Private Inner Class Static Inner Class Facebook X
Comments 0
Similar posts
  1. Java Polymorphism
    7,051
  2. Java Inheritance (Subclass and Superclass)
    7,178
  3. Java Packages
    7,174
  4. Java Classes and Objects
    7,077
  5. Java Recursion
    7,197
  6. Java Scope
    7,089
  7. Java Methods
    7,080
  8. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,845
  9. Java Switch Statements
    7,402
  10. Java Short Hand If...Else (Ternary Operator)
    7,571
  11. Java If ... Else
    7,391
  12. Java Math
    7,429
  13. Java Variables
    7,459
  14. Java Comments
    8,000
  15. The Print() Method
    7,148
  16. Java Syntax
    7,434
  17. Java Getting Started
    7,406
  18. What is Java?
    7,088
  19. Machine Learning Types and Programming Languages
    7,228
  20. Java Tutorials associated with AP Computer Science A
    7,597
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,164
  22. Java Servlet Example
    7,114
  23. Difference between Java and Javascript
    7,604
  24. Challenge: One Code Problem Per Day
    1,092
  1. Java Servlet Example
    7,114
  2. How do I replace content that based on the HTML UI Template
    7,153
  3. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,164
  4. Dataset of California Foodbanks
    7,169
  5. Java Tutorials associated with AP Computer Science A
    7,597
  6. Java Polymorphism
    7,051
  7. Java Inheritance (Subclass and Superclass)
    7,178
  8. Java Packages
    7,174
  9. Java Abstract Classes and Methods
    7,718
  10. Java Classes and Objects
    7,077
  11. Java Recursion
    7,197
  12. Java Scope
    7,089
  13. Java Methods
    7,080
  14. Java Arrays
    8,690
  15. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,845
  16. Java Switch Statements
    7,402
  17. Java Short Hand If...Else (Ternary Operator)
    7,571
  18. Java If ... Else
    7,391
  19. Java Math
    7,429
  20. Java Variables
    7,459
Recently updated
  1. Watch This Dazzling Dancer’s Mind-Blowing Moves
    42
  2. Michael Jackson's Billie Jean
    123
  3. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    138
  4. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    405
  5. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    231
  6. The Evolution and Production Reality of Agentic AI
    214
  7. How to Activate or Waive Your UIUC Student Health Insurance
    296
  8. Complete Guide to Building a Machine Learning Model
    324
  9. My life cuts at Las Vegas during Thanksgiving day holiday
    7,407
  10. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    351
  11. Harness vs. OpenClaw: Two Very Different "Agents"
    979
  12. Clean Python Environments: The Power of venv vs. Docker
    824
  13. What is Docker? Why is Docker also useful in a development environment?
    621
  14. UIUC 2026-2027 Academic Calendar
    1,594
  15. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    810
  16. Open-Source LLMs: The AI Revolution
    761
  17. Resume 2.0: Leveling Up for My First Software Gig
    2,223
  18. Not everyone will understand what this man just did
    1,883
  19. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,594
  20. Unpacking IU's Shopper
    769
  21. Jackie Chan's Police Story: The Action Masterpiece
    658
  22. The IVE Story: Identity, 'I AM' Charts, and Influence
    967
  23. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,187
  24. Open Databases for Sex Crime Occurrences in the U.S.
    716
  25. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,650
  26. My First Day at University of Illinois-Urvana Champaign
    1,195
  27. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,134
  28. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,215
  29. Sipping the Stars: My Starbucks Adventure
    9,656
  30. Exciting explore at Sequoia National Park
    7,664
  31. My Life Shot at Death Valley
    1,709
  32. Ip Man fights with Muay Thai Master
    944
  33. Mad Clown - Don't Die
    1,024
  34. How to get Student Enrollment and Degree Verification at UIUC
    4,898
  35. LAX Thanksgiving Rush: A Joyful Reunion
    924
  36. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,130
  37. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    985
  38. 10CM - To Reach You (너에게 닿기를)
    1,159
  39. Feeling weak? Transform yourself at the UIUC ARC!
    1,573
  40. BOYNEXTDOOR - If I Say I Love You
    1,188
  41. The Future of Software Engineer - AI Engineering
    932
  42. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    915
  43. Lie - Legend song by BIGBANG
    7,820
  44. Why ROLLBACK is useful when you work with Google Gemini CLI?
    842
  45. Reimbursement after Vaccination at McKinley Health Center
    1,022
  46. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    968
  47. Common Questions from UIUC school life in terms of CS Program
    1,123
  48. UIUC Immunization Compliance
    1,213
  49. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,097
  50. LEE CHANHYUK - Endangered Love (멸종위기사랑)
    1,096