Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Static vs inner class [duplicate]

What is the difference between static and non-static nested class?

like image 527
Abhishek Sanghvi Avatar asked Aug 30 '09 07:08

Abhishek Sanghvi


People also ask

What is the main difference between an inner class and a static nested class in Java?

1) First and most important difference between Inner class and nested static class is that Inner class require instance of outer class for initialization and they are always associated with instance of enclosing class. On the other hand nested static class is not associated with any instance of enclosing class.

What is the difference between static and non-static inner class?

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Does inner class have to be static?

Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kinds of classes in Java, one is called a top-level class and the other is called a nested class.

Why do we need static inner class?

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.


2 Answers

An inner class, by definition, cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?"

A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.

like image 179
Brandon E Taylor Avatar answered Oct 16 '22 08:10

Brandon E Taylor


Let's look in the source of wisdom for such questions: Joshua Bloch's Effective Java:

Technically, there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class. A non-static nested class is indeed an inner class, along with anonymous classes and local classes.

And now to quote:

Each instance of a non-static nested class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance.

A static nested class does not have access to the enclosing instance. It uses less space too.

like image 26
Steve McLeod Avatar answered Oct 16 '22 09:10

Steve McLeod