
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Different Types of Nested Classes in Java
In Java, it is possible to define a class inside another class, such classes are called Nested classes. We can use the access modifiers like private, public, protected or default for inner classes and default or public access modifiers for outer class.
There are two types of nested classes are defined in Java.
- Static Nested Class
- Non-Static Nested Class
Static Nested Class
- We Can define an inner class as static, so such type of classes is called a static nested class.
- The nested class is defined with the static keyword, so this type of nested classes doesn’t share any relationship with the instance of an outer class.
- A static nested class can able to access the static members of our class.
Example
class Car { static class Wheel { public void rotate() { System.out.println("The wheel is rotating"); } } } public class Test { public static void main(String args[]) { Car.Wheel wheel = new Car.Wheel(); wheel.rotate(); } }
Output
The wheel is rotating
Non-Static Nested Class
- A non-static nested class is indirectly known as an inner class in Java.
- The inner class is associated with the object of the outer class. So the inner class is treated like other variables and methods of the outer class.
- The inner class is associated with the outer class object or instance, so we can’t declare static variables inside the inner class.
Example
public class OuterClassTest { private int a = 10; public void innerClassInstance() { InnerClassTest inner = new InnerClassTest(); inner.outerObject(); } public static void main(String args[]) { OuterClassTest outer = new OuterClassTest(); outer.innerClassInstance(); } class InnerClassTest { public void outerObject() { System.out.println("Outer Value of a is: " + a); } } }
Output
Outer Value of a is: 10
Advertisements