Java Inner Classes

JK JK 2038 
Created at
Updated at  
7,159 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,137
  2. Java Inheritance (Subclass and Superclass)
    7,251
  3. Java Packages
    7,256
  4. Java Classes and Objects
    7,203
  5. Java Recursion
    7,267
  6. Java Scope
    7,199
  7. Java Methods
    7,174
  8. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    8,039
  9. Java Switch Statements
    7,508
  10. Java Short Hand If...Else (Ternary Operator)
    7,681
  11. Java If ... Else
    7,504
  12. Java Math
    7,534
  13. Java Variables
    7,579
  14. Java Comments
    8,203
  15. The Print() Method
    7,232
  16. Java Syntax
    7,554
  17. Java Getting Started
    7,501
  18. What is Java?
    7,161
  19. Machine Learning Types and Programming Languages
    7,337
  20. Java Tutorials associated with AP Computer Science A
    7,769
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,268
  22. Java Servlet Example
    7,195
  23. Difference between Java and Javascript
    7,739
  24. Challenge: One Code Problem Per Day
    1,269
  1. How do I replace content that based on the HTML UI Template
    7,228
  2. Dataset of California Foodbanks
    7,246
  3. Java Abstract Classes and Methods
    7,895
  4. Java Arrays
    9,038
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    835
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    738
  3. Michael Jackson's Billie Jean
    378
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    324
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    314
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    342
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    358
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    372
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,225
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    526
  11. The Evolution and Production Reality of Agentic AI
    407
  12. How to Activate or Waive Your UIUC Student Health Insurance
    520
  13. Complete Guide to Building a Machine Learning Model
    528
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,593
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    563
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,330
  17. Clean Python Environments: The Power of venv vs. Docker
    1,083
  18. What is Docker? Why is Docker also useful in a development environment?
    795
  19. UIUC 2026-2027 Academic Calendar
    1,982
  20. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,048
  21. Open-Source LLMs: The AI Revolution
    963
  22. Resume 2.0: Leveling Up for My First Software Gig
    2,925
  23. Not everyone will understand what this man just did
    2,410
  24. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,836
  25. Unpacking IU's Shopper
    964
  26. Jackie Chan's Police Story: The Action Masterpiece
    841
  27. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,173
  28. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,367
  29. Open Databases for Sex Crime Occurrences in the U.S.
    944
  30. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,348
  31. My First Day at University of Illinois-Urvana Champaign
    1,363
  32. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,391
  33. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,465
  34. Sipping the Stars: My Starbucks Adventure
    10,110
  35. Exciting explore at Sequoia National Park
    7,845
  36. My Life Shot at Death Valley
    2,032
  37. Ip Man fights with Muay Thai Master
    1,118
  38. Mad Clown - Don't Die
    1,235
  39. How to get Student Enrollment and Degree Verification at UIUC
    5,786
  40. LAX Thanksgiving Rush: A Joyful Reunion
    1,068
  41. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,341
  42. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,139
  43. 10CM - To Reach You (너에게 닿기를)
    1,319
  44. Feeling weak? Transform yourself at the UIUC ARC!
    1,726
  45. BOYNEXTDOOR - If I Say I Love You
    1,362
  46. The Future of Software Engineer - AI Engineering
    1,085
  47. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,094
  48. Lie - Legend song by BIGBANG
    7,990
  49. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,088
  50. Reimbursement after Vaccination at McKinley Health Center
    1,199