Static Nested/Inner Class Example

Java Inner Class :
What is an Inner Class?
Inner classes are also known as Nested class, is a class which is declared within another class.

Advantages of Inner Class:

  • Inner class can access all the variables and methods of enclosing class including private members
  • Useful for Interface Implementations used by enclosing class
  • Fine control over interface implementation

Types of Inner Classes:
There are 4 types of Inner Classes,

  • Static Nested Class
  • Member Inner Class
  • Method Local-Inner Class
  • Anonymous Inner Class

Static Nested Class:
A class within another class is known as Static Nested Class

Member Inner Class:
Class created within a class but outside methods

Method Local-Inner Class:
Class created within a methods

Anonymous Inner Class:
Class created for implementing interface or extending class

Today, In this article we are going to see an example of Static Nested Class i.e. Class within a class

Syntax for creating object for Inner Class,

OuterClassName.InnerClassName ObjectofInnerClass = InnerClassName();

This syntax may look like complex one, But once we are through with the code we can understand it easily.

In this code, We have declared private method and a private variable in the outerclass and that has been accessed by the Inner class.

OuterClassName.InnerClassName ObjectofInnerClass = InnerClassName();

Creating object for Inner class,
InnerExample.Inner inner = innerexample(OuterclassObject).new Inner();




Leave a Reply

Your email address will not be published. Required fields are marked *