Java

Static and Non Static Inner Class in java with Examples using netbeans

Example of Using Inner Class in Java

Inner Class in java is a class (inside a class or nested class) in which class (outer class), class is a model framework/blueprint that is used as a place to put attributes such as variables, methods, constructors, etc. In java programming, we can add a class (internal class) inside the class (outer class) or it can be called Nested Class, another example is the if conditioning syntax, that is, we can add if inside the if. Inner Class in java has access rights to attributes or methods that are in the Outer Class even though it is in a private modifier condition, on the other hand, the Outer Class does not have access rights to the Inner Class.


Related Articles:

Inner Class in Java

Basically, Inner Class or Nested Class in java is used to group classes in one place and create readable and maintainable code in Java.



Basic Syntax of Inner Class in java:

the basic syntax for creating Inner Classes in java is as follows:

Because an Inner Class uses an Instance of an Outer Class, its members cannot be declared statically.

There are 2 types of Inner Class in Java, namely non-static and static, in this tutorial we will discuss the two types of Inner Class with examples.

Non-static Inner Class in java:

Non-static Inner Class is a class that is not at the top level or a class declared in another class (Outer class). To access variables or methods in the outer class, we need to create an Instance/Object of the Outer Class in the Inner Class. The Inner class in java requires an Instance/Object from the Outer Class to directly access the method or its variables, then we Instance the Inner Class. The source code is as follows:


Example: Non-static Inner Class in java using NetBeans:

Output:

Inner Class

I have explained before, Inner Class can be used to group something if we have several classes that have different functions.


Static Inner Class in java

To change the Inner Class to static, we only need to add the static keyword behind the class. What distinguishes a static class from a non-static class is that in a static class we don’t need to Instance/Create an object from an Outer class first, a static Inner Class only needs to create an instance of a class Inside only.

Static inner classes in java are easier and more practical to use than non-static ones. A simple example is as follows:


Example: Static Inner Class in java using NetBeans:

output:

Inner Class

Hopefully, the tutorial that I provide can be useful for you.

Related Articles

Leave a Reply

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

Back to top button