- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Nested Classes in Java
Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. Nested classes are divided into two types −
Non-static nested classes (Inner Classes) − These are the non-static members of a class.
Static nested classes − These are the static members of a class.
Following are the types of Nested classes in Java −
Non-static nested classes (Inner Classes)
Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.
Let us see an example −
Example
class Outer_Demo { int num; // inner class private class Inner_Demo { public void print() { System.out.println("This is an inner class"); } } // Accessing he inner class from the method within void display_Inner() { Inner_Demo inner = new Inner_Demo(); inner.print(); } } public class My_class { public static void main(String args[]) { // Instantiating the outer class Outer_Demo outer = new Outer_Demo(); // Accessing the display_Inner() method. outer.display_Inner(); } }
Output
This is an inner class.
Static Nested Classes
A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
Let us see an example −
Example
public class Outer { static class Nested_Demo { public void my_method() { System.out.println("This is my nested class"); } } public static void main(String args[]) { Outer.Nested_Demo nested = new Outer.Nested_Demo(); nested.my_method(); } }
Output
This is my nested class
- Related Articles
- Static Nested Classes in Java
- Nested Classes in C#
- Nested Classes in C++
- C# Nested Classes
- What are nested classes in C#?
- What are the different types of nested classes are defined in Java?
- Abstract Classes in Java
- Nested interface in Java
- Explain wrapper classes in Java?
- What are final classes in Java?
- What are abstract classes in Java?
- What are inner classes in Java?
- What are wrapper classes in Java?
- Abstract Method and Classes in Java
- What are Java classes?
