DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowBack To SchoolAmazon USBack-to-school picks: upgrade before the busy seasonAmazon US: study, desk and setup picks worth checking.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
THEGEEKSCLUB

How to Instantiate an Inner Class – Nested Class in Java

Instantiate an Inner Class
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Java programming language, when a class is defined within another class, then such a class is called a nested class or inner class. Nested classes are a unique feature of Java that has been included since jdk1.1. Always remember, this nesting functionality is a relationship between classes only, not between Java objects. Previously we have talked about how to instantiate instance variable in Java, and now we will take a look at how to instantiate an inner class in Java.

How to Instantiate an Inner Class – Nested Class in Java

  1. Types of Nested Classes
    • Non Static
    • Static
  2. Access Modifiers for Nested or Inner Classes
  3. Features of Nested Class
  4. Advantages
  5. Sample code, explanation of code & output

Types of Nested Classes in Java

Non-static Nested Class

Non-static nested classes are called inner classes. It has access to all of its enclosing class’s instance data, including private fields and methods.

Syntax

[modifiers] class OuterClassName {
  code...
  [modifiers] class InnerClassName {
    code....
  }
}

Creation

<OuterClassName> outerObj = new <OuterClassName>(arguments);
<OuterClassName>.<InnerClassName> innerObj = outerObj.new <InnerClassName> (arguments);

Properties

  1. The outer class (the class containing the inner class) can instantiate as many numbers of inner class objects as it wishes, inside its code.
  2. If the inner class is public & the containing class as well, then code in some other unrelated class can as well create an instance of the inner class.
  3. No inner class objects are automatically instantiated with an outer class object.
  4. The inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is), if the inner class has a variable with the same name then the outer class’s variable can be accesse like this:
    <OuterClassName>.this.<variableName>
  5. The outer class can call even the private methods of the inner class.
  6. The inner class object must be associated with an instance of the outer class.

Static Nested Class

Nested classes that are declared static are just called static nested classes. A static class has no access to instance-specific data.

Syntax 

<access-specifier> class OuterClassName {
  public static class <StaticInnerClassName> {
      code. . .
  }
  code . . .
}

Creation

<OuterClassName>.<InnerClassName> innerObj = new <OuterClassName>.<InnerClassName>(arguments);

Properties

  1. For static inner class, then the static inner class can be instantiated without an outer class instance.
  2. Static members of the outer class are visible to the static inner class, what ever their access level is.
  3. Non-static members of the outer class are not available, because there is no instance of the outer class.
  4. An inner class may not have static members unless the inner class is itself marked as static.
  5. Sometimes static nested classes are not referred to as inner class at all, as they don’t require outer class’s instance.
  6. A static inner class is just like any other inner class, but it does not have the reference to its outer class object that generated it.

Access Modifiers for Nested or Inner Classes

  • public
  • protected
  • private
  • default
Learn more about Java access specifiers/modifiers here.

Features of Nested Class

An object of an inner class has an implicit reference to the outer class object that instantiated it. Through this pointer, it gains access to any variable of the outer object. Only static inner classes don’t have this pointer but can access all the static members only using the outer class name. It is actually invisible when we write the code, but compiler takes care of it. Inner classes are actually a phenomenon of the compiler and not the JVM. This feature makes Java inner classes richer and more useful.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Shopping ad
Sale
FYY Electronic Organizer, Travel Tech Pouch Bag, Cable Organizer Black
  • Dimensions: 7.5" x 4.3" x 2.2". Compact size and lightweight make it easy to carry and put into your backpack, handbags or laptop bag without taking much space. Suitable for family use and daily organization. Note: Small mesh pockets are ideal for charging cords no longer than 3ft; longer cables (over 3ft) fit better in the larger compartments
  • Quality Material: This electronic organizer travel case made of high quality durable waterproof oxford and soft sponge inside to secure your gadgets in place and deliver a quick access whenever you want. Water-resistant fabric protects your gear from unexpected splashes, keeping all your electronic essentials safe and secure
  • Double Layers Design: This tech pouch features a double-layer interior design with 8 compartments, including multiple see-through mesh pockets and ample space to store your cords, cables, USB drives, cellphone, charger, mouse, flash drive and more, keeping all accessories neatly organized and tangle-free
  • Practical and Convenient: Comes with a comfortable hand strap for easy carrying; You may carry it in your hand when heading out. Durable and smooth zipper closure keeps your favorite device securely, convenient for you to have quick access to the items inside the case
  • Portable and Lightweight: The small size and lightweight design durable cable organizer pouch is a perfect choice when going on holiday, business trip, travel, office. Enjoy hassle-free travel without wasting time on tangled accessories. Great gift for yourself also a nice share with families and friends. (No include cords, electronic accessories)

Advantages of Nested Class

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.
  • Logical grouping of classes – If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such as “helper classes” makes their package more streamlined.
  • Increased encapsulation – Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A’s members can be  private, but B can access them. Also, B itself can be hidden from the outside world.

Program 1

/* within the scope of outer class */
class Outer{
  int var1 = 2;
  int var2 = 3;

  /* Inner Class */
  class Inner{
    void add(){
      System.out.println("Addition is:"+(var1+var2));
    }
  }

  void show(){
    Inner in = new Inner();
    in.add();
  }
}

class NestedClassDemo{
  public static void main(String args[]){
    Outer out = new Outer();
    out.show();
  }
}

Output 1

code for nested class in java

Program 2

/* Outside the scope of outer class */
class Outer{
  int var1 = 2;
  int var2 = 3;

  /* Inner Class */
  class Inner{
    void add(){
      System.out.println("Addition is:"+(var1+var2));
    }
  }
}

class NestedClassDemo1{
  public static void main(String args[]){
    Outer.Inner in = new Outer().new Inner();
    in.add();
  }
}

Output 2

code for nested class in java

Explanation of Code & Output

In the first program, we have instantiated the nested class Inner in a method declared within the Outer class i.e.

within the scope of the outer class. We will specially instantiate inner classes within the scope of the outer class. The inner class is Private as we know private members will not be accessible outside the scope of that class containing private members.

Shopping ad
Ordilend Keyboard Cleaner & Laptop Cleaning Kit, All-in-1 for Computer PC
  • 【UPGRADED LAPTOP CLEANING KIT 】 The macbook cleaning kit computer screen cleaner comes with a number of accessories including a retractable large brush, polishing cleaning cloth X 2, keycap puller, metal pen tip, flocking sponge, thin soft brush, soft plastic lens cleaning pen, 5 replacing cloth, large cleaning microfiber cloth. You deserve the comprehensive computer cleaning kit keyboard vacuum at a low cost
  • 【PROFESSIONAL KEYBOARD CLEANING KIT】 The laptop screen cleaner keyboard cleaner can pull out the keycaps of gaming keyboards and mechanical keyboards. A retractable keyboard brush works on laptops and keyboards, while the mini high-density brush is great for deep cleaning between keys for cleaning between flatter keys on a laptop, the metal pin tip gently removes any stains. This electronic cleaning kit macbook cleaner totally meets professional cleaning needs
  • 【OFFICE DESK ACCESSORIES】This keyboard cleaner kit is easy to use and can clean your keyboard and electronic screen with just one swipe. Wiping with the 2mm thicken widen polishing cleaning cloth designed at a right angle for better fitting screen corners of computers with our recyclable cleaning spray, The laptop cleaner kit for macbook effectively absorbs stubborn stains, leaves no discoloration, no streaks, and no fiber shedding on the screens
  • 【MULTIFUNCTIONAL TOOLS 】Mini soft brush and soft plastic lens cleaning pen are specially designed for DSLR camera screen, lens, and other delicate surfaces. 5 more cleaning cloths of it supplied for replacement. The flocking sponge is an excellent tool for cleaning earbuds charging cases, And the earbud cleaning kit is ideal. This electronics for college students is equivalent to 10 other electronic cleaning kit
  • 【PORTABLE DESIGN & CLEANER TOOL】 The office supplies is compact in design, easy to carry, and you can easily take it anywhere. It's convenient to keep one in a drawer, one in your car, or in your bag and dorm. It is easy to use and can clean your keyboard and electronic screen with just one swipe. Is the college essentials cleaning tool for your friends, family, colleagues and students

In the second program, we have instantiated the nested class Inner outside the scope of Outer class. The syntax seems to be difficult, but it’s not like that. It’s too easy:

We will break this statement into two:

Outer out =  new Outer();
Outer.Inner in = out.new Inner();

First, we have to create an object for the outer class. Then we will create an object for the Inner class as Inner class is the member of Outer class, so we have to recognize the Inner class uniquely, can be done with Outer. Inner then we have to create the object which is done by a new operator followed by the constructor of that particular class. The same thing is done here.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Shopping ad
Sale
BAGSMART Large Electronic Organizer Travel Case for Tech Accessories, Black
  • Compatible Space: This electronics organizer bag features 2 zippered mesh pockets fits phones, standard power banks, 4 elastic loop pouches for small items, 2 elastic loop pouches for wireless headphones and small chargers. Elastic loops for phone charging cable. And specific slots for SD cards. Please check the size to ensure it meets your needs
  • Lightweight Travel Accessories: The size of the electronic organizer travel case is 10.6" L x 7.5" W x 1.2" H, Compact but substantial size fits your intended bag or space. Suitable for traveling use and daily organization
  • Keep Everything Organized: This compact travel organizer features dedicated compartments for your phone charger, cables, and tech accessories, keeping them tangle-free and ready to go. You can find travel accessories quickly, no chasing cords in your pack anymore
  • Durable Travel Essentials: Features double zippers for easy access, elastic loops with non-slip grips for daily protection. Organizer for office use and traveling, (Not including cords, electronic accessories). It can serve as a travel checklist. Before you leave a place, just open the case and check if everything is there, preventing you from leaving things behind
  • Versatile Use: Its practicality and convenience make it a travel essential bag. It is suitable for a weekend trip, business trip, and travel. This organizer pouch is suitable for office, business, daily use and can be given as a gift for friends, family, or men, for birthdays, Valentine's Day, Christmas Day, Father's Day

Flash on

After compiling the nested class, two .class files will be generated with Outer.class and Outer$Inner.class (here class Inner is inside class Outer).

Checkout more useful tutorials and definitive guidelines on Java programming.

Shopping ad
Sale
HOTO Pocket-Size Laser Measuring Tool, EDC Gadget Birthday Gift for Men Dad
  • Award-Winning Compact Design & EDC-Ready Gift Choice: Weighing only 0.09 lb and sized like a credit card, this compact laser measure is designed for everyday carry. It slips easily into a pocket, tool pouch, or bag, and can attach to a keychain for quick access wherever you go. Its minimalist design, premium tactile finish, and practical one-button measuring make it a useful EDC gadget for DIYers, real estate agents, homeowners, and tech enthusiasts. A thoughtful gift for men on any occasion
  • One-Button Easy Measuring, Simple to Use: Designed with simple one-button operation, this compact laser tape measure makes quick measuring easy without complicated controls. Just press to measure room dimensions, furniture spacing, window height, wall décor placement, and everyday distances around the home. Ideal for users who want a smart, pocket-size measuring tool that fits naturally into an everyday carry (EDC) setup and feels intuitive, modern, and easy to use
  • Fast & Accurate Indoor Measurements with Class 2 Laser: Measure distances from 0.16 ft to 98 ft with up to ±1/16 in / ±2 mm accuracy. With quick measurement response in about 0.2 seconds, HOTO helps you check spaces efficiently for home renovation, furniture layout, moving, decorating, craft projects, and DIY planning. Built with a Class 2 laser for everyday indoor measuring; use as directed and avoid direct eye exposure
  • Low-Power OLED Display & USB-C Rechargeable Convenience: The low-power OLED display provides clear indoor readings while helping reduce battery drain. With USB-C rechargeable design, auto shut-off, and up to 1000 measurements per charge, this digital laser measure is built for repeated daily use without frequent battery replacement. Compact enough to keep in a drawer, toolbox, bag, or pocket
  • Useful for Home, Work & Everyday Projects: From home renovation and furniture measuring to room planning, real estate checks, interior design, and light construction projects, this pocket-size laser distance measure is made for practical everyday use. Compact enough to keep in a drawer, toolbox, bag, or pocket, it is a stylish measuring tool that feels just as giftable as it is useful
Shopping ad
Sale
ColorCoral Cleaning Gel Universal Dust Cleaner for PC Keyboard Car Detailing Office Electronics Laptop Dusting Kit Computer Dust Remover, Computer Gaming Car Accessories, Gift for Men Women 160g
  • Universal fit: ColorCoral cleaning gel, simple and convenient cleaning kits for PC/laptop keyboard and other rugged surface, such as the car vent, camera, printer, telephone, calculator, Instrument, speaker, air conditioner, TV and other appliances
  • Safe cleaning gel: The keyboard cleaner gel is made from natural gel, no sticky to hands, smells sweet with lemon fragrance, no stimulation to skin
  • Easy dust cleaning: Make sure your hands are dry and clean, knead the cleaning gel into a ball, press the cleaning gel slowly into the keyboard, car vent and rugged surface till the cleaning gel could touch the bottom and then pull out, the dust would be carried away with the cleaning gel
  • Reusable: The keyboard cleaning gel could be used repeatedly till the color turn to dark or it become sticky, then you have to replace the cleaning gel with a new one. After cleaning, please stock the cleaning gel in cool place. (Note: Don’t wash the gel in water.)
  • In the package: 1 can of universal cleaning gel, we provide the cleaning gel with brand new, if you find the package broken, the cleaning gel dirty, or any other quality issues, please email us through message, we provide you new one soon

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi
Avatar photo
Written by

Nitin Agarwal

A blogger, tech evangelist, YouTube creator, books lover, traveler, thinker, and believer of minimalist lifestyle.

More from this author ↗
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.