Understanding Static Class in Java | Java Nested Class

7 Chapters deep, it is high time we understood what Static Class in Java is all about. Why use Java Static Variable? How to make a method or variable static and how to call a method using Static Class? We will see all of that here. I hope by the time we reach the end of this post, we might feel like a know-all smug version of Yoda.

Yoda Meme joke for static class in Java

The cardinal reason static keyword was brought into usage was because it helped in dealing with memory related issues.

For example, if you make a data member static, only one copy of that particular variable is made and is shared by all the objects of the class. Au contraire, a non-static variable or an instance variable is created every time we instantiate a new object of the class.

If you make a class method static, you can call it without instantiating the object. All you have to do is use the Class Name with the dot operator to call the method.

Confused? Don’t worry we are going to see things in detail.

What is a Static Class in Java?

Remember how we have been defining a class inside another class so far for all our coding scenarios? This is typically called as nesting.

Also, you might have noticed how we had never made our top level class as static. The reason is plain and simple. Because in Java it can’t be done! Only a class that is nested can be turned into a static class in Java.

That being said we must understand that using static classes is simply great for grouping purposes. Because Java allows us to group classes that are useful to each other, we group them just to keep them together under a single keyword static.

So for example there are two classes that are almost related to each other, we can group them against each other by using static, and then leave the other unrelated one alone.

Static and Non-Static Nested Classes

Nested Classes are nothing but inception of classes. Classes inside classes.

You remember That 70s Show right? I will dumb things down by taking it as an example:

public class Eric {

       public class Donna {

       void method1(){}

       }

       public class Red {
         
       void method2(){}
       
       }

}

In the example above we have Donna and Red both nested classes of Eric. Remember Eric is the top level class so it can’t be made static. So, that leaves us with Donna and Red. Eric is in love with Donna, meaning it would be wise of us to make Donna static.

public class Eric {

       public static class Donna {

       void method1(){}

       }

       public class Red {
         
       void method2(){}
       
       }

}

Now since Donna has been turned into a static class, if we are planning on using its method in the long run, we must make it static too. So the above code will finally look like:

public class Eric {

       public static class Donna {

       void static method1(){}

       }

       public class Red {
         
       void method2(){}
       
       }

}

Got it? We will plunge in deeper and write our code from scratch to understand everything better.

Things to Remember

While working with Static Classes, you must remember:

  1. It cannot access non-static data member or methods. So if you are planning on calling a non-static data member you must first make that data member static by using the static keyword like we did in the final part of how to use classes in java chapter.
  2. If you make a class method as static, in order to call it you don’t have to instantiate it (create its object). Simply use the name of the class followed by the dot operator and then the method name. That should do it.

Data Members

To understand static class in java, you must fathom what static and non-static data members are first.

There are two types of data members in Java.

They are namely:

  1. Static
  2. Non – Static or Instance

Now when I say data members it includes both variables and methods. So that means not only can we make our fields static we can make our methods static too.

To make any field or method static, all we have to do is use the keyword static before its declaration.

The same holds true for method. Simply use the keyword static while declaring it, and your method becomes static.

Here is one example of static variable and method:

static variable and method example

For non-static data members, you don’t need to use any keywords. This means by default they are always non-static.

We will take the above example forward and try to understand how to call the static method say() via main.

Calling a Static Nested Method

A static Class in Java can have a static method. It is not necessarily the requirement but if you use a non-static method inside a static class in Java it will flare an error.

Calling a static method is easy since it doesn’t entail creating an object at all. Yes, as mentioned above all we need is the name of the Outer Class and the nested one and we are good to go. you have to do is use the name of the Class

The syntax to call a static nested method is:

OuterClassName.InnerClassName.methodname();

Simply replace the Class Names and method name with the suitable ones. Do not forget to use the dot operator in order to separate all the entities.

Using the above in our main method to call the static method our code might appear something like this:

image for calling a static method

Notice how we have used Eric.Donna.say() in the above example, since Eric and Donna are our Outer and Inner Class Names. We have eventually called the method say().

Let’s execute it and see if our method is being called or not. On Running the program this is what I get:

result of calling a static method in Java

Hurray!

We have successfully called the say() method by using the correct syntax.

I will quickly display the static variable too.

Since our main method is static and we are calling a static variable, we should not get any error.

image to display static variable in main method

Run the program. You should get the following answer:

final output for static method and variables

How to Call a Non – Static Nested Method

Time to go back to what we were trying to understand in the beginning. We will insert a non – static nested class called Red(). And put a method named red() to display a message:

image for a non-static class Red and its methodNow our Class Red is actually a nested class just like Donna was. The only difference here is that latter was static.

Here is how the nested class Red fits in:

static and non-static classes in java

Now it is time we called the method red() of Red class.

Creating an Object of Non-Static Nested Class

Since Red is a sub-class of Eric, we are going to have to create an object of Eric first. We are going to do that by writing the following code in our main method:

Eric eric = new Eric();

The above has instantiated an object named ‘eric’.

Now it is time to create an object of the class Red for which we are actually rooting for. Write it like this:

Red er = eric.new Red();

Fairly simple eh! What we are doing is trying to create an object ‘er’ in our regular way and then making use of the instance that we had create a step ago, and following it by the dot operator, immediately ending it with the non-static nested class name.

So our final code might look something like this:

create an object of non static nested class

Now it is time to call the method.

Since, this one’s no static class, the old rules apply to this. Simply type

er.red();

and you are done.

Run the program, and find the following answer:

image for output when you call a static and non-static method

Another alternative to writing a single line code for the above painful two liner is:

one liner for creating static and non-static objects

It should get you the same result.

Go ahead and run it.

Usage of Static

Remember how we have been using the keyword ‘static’ in our main method? Yes in the code “public static void main” we were writing static in our main method? I hope the following explanation will make you understand why:

Static fields are associated with a class. It gets memory only once when the class is loaded.

Using a static field is actually useful when there is an array involved where the class is loaded many times. It would execute your code quickly since it doesn’t have to load every time array reaches out for putting data in its cell. Also, the usage of static comes handy when you are working with counters.

Static methods are generally used when you wish to change a static variable. Because there’s no other way to do that since when the class is loaded static variable is only created once, and the value stays the same for the class. To change that you would need a method, a static method to be precise.

I think with that we have covered static class in Java pretty well.

Bottom Line

So the bottom-line is, if someone asks you what is static and why do you use it? This is the nutshell you should give him:

  • It is basically used for memory management.
  • Static methods and variables are loaded only once, and only one copy of it is created when you run the program.
  • We can make any variable, method, block or nested class static by preceding the keyword static.
  • Only a static method can change the value of static variable.
  • You cannot use a static variable from a non-static method, and vice versa.
  • The top level class can’t be static.
  • Nested classes can be both static and non-static.
  • Both these classes have special ways to call their respective methods. While a nested static class can be called without instantiating, the nested non-static one needs to be called by creating two objects in a fashion mentioned above.

That’s all there is to learn in static class in Java.

Phew! I am drained. Java does that to you, I guess.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

5 Responses

  1. May 30, 2017

    […] of our code for our java demo program says static. To learn what is static you need to check this static chapter […]

  2. June 3, 2017

    […] Hope you remember your Static basics, if not go back to the chapter about static class and methods. […]

  3. June 12, 2017

    […] implied by the definition of static, when you want the lock on the “class” and not on the object you make use of static […]

  4. April 4, 2018

    […] are we making it static? Go back to understand that we can’t use a non-static variable in a static […]

  5. July 28, 2019

    […] Java – Chapter 8 | Understanding Static Class in Java | Java Nested Class | Dumb IT DudeApril 23, 2017 […]

Leave a Reply