Java Inner Classes

JK JK 2034 
Created at
Updated at  
7,101 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,086
  2. Java Inheritance (Subclass and Superclass)
    7,203
  3. Java Packages
    7,209
  4. Java Classes and Objects
    7,143
  5. Java Recursion
    7,223
  6. Java Scope
    7,142
  7. Java Methods
    7,128
  8. Java While Loop/Do While Loop/For Loop/For-Each Loop/Break/Continue
    7,957
  9. Java Switch Statements
    7,451
  10. Java Short Hand If...Else (Ternary Operator)
    7,626
  11. Java If ... Else
    7,449
  12. Java Math
    7,476
  13. Java Variables
    7,518
  14. Java Comments
    8,116
  15. The Print() Method
    7,192
  16. Java Syntax
    7,501
  17. Java Getting Started
    7,447
  18. What is Java?
    7,127
  19. Machine Learning Types and Programming Languages
    7,289
  20. Java Tutorials associated with AP Computer Science A
    7,708
  21. Creating a simple Java Servlet (Web Server Page) with Apache Maven on Microsoft Windows
    7,215
  22. Java Servlet Example
    7,156
  23. Difference between Java and Javascript
    7,689
  24. Challenge: One Code Problem Per Day
    1,196
  1. How do I replace content that based on the HTML UI Template
    7,190
  2. Dataset of California Foodbanks
    7,205
  3. Java Abstract Classes and Methods
    7,803
  4. Java Arrays
    8,844
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    50
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    83
  3. Michael Jackson's Billie Jean
    286
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    115
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    180
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    197
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    219
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    257
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    787
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    408
  11. The Evolution and Production Reality of Agentic AI
    324
  12. How to Activate or Waive Your UIUC Student Health Insurance
    411
  13. Complete Guide to Building a Machine Learning Model
    437
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,526
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    462
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,152
  17. Clean Python Environments: The Power of venv vs. Docker
    975
  18. What is Docker? Why is Docker also useful in a development environment?
    715
  19. UIUC 2026-2027 Academic Calendar
    1,802
  20. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    928
  21. Open-Source LLMs: The AI Revolution
    880
  22. Resume 2.0: Leveling Up for My First Software Gig
    2,560
  23. Not everyone will understand what this man just did
    2,134
  24. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,720
  25. Unpacking IU's Shopper
    889
  26. Jackie Chan's Police Story: The Action Masterpiece
    763
  27. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,078
  28. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,294
  29. Open Databases for Sex Crime Occurrences in the U.S.
    836
  30. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,978
  31. My First Day at University of Illinois-Urvana Champaign
    1,292
  32. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,289
  33. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,374
  34. Sipping the Stars: My Starbucks Adventure
    9,873
  35. Exciting explore at Sequoia National Park
    7,786
  36. My Life Shot at Death Valley
    1,878
  37. Ip Man fights with Muay Thai Master
    1,051
  38. Mad Clown - Don't Die
    1,149
  39. How to get Student Enrollment and Degree Verification at UIUC
    5,281
  40. LAX Thanksgiving Rush: A Joyful Reunion
    1,011
  41. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,244
  42. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,080
  43. 10CM - To Reach You (너에게 닿기를)
    1,255
  44. Feeling weak? Transform yourself at the UIUC ARC!
    1,667
  45. BOYNEXTDOOR - If I Say I Love You
    1,281
  46. The Future of Software Engineer - AI Engineering
    1,016
  47. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,009
  48. Lie - Legend song by BIGBANG
    7,917
  49. Why ROLLBACK is useful when you work with Google Gemini CLI?
    962
  50. Reimbursement after Vaccination at McKinley Health Center
    1,119