Can we declare a class Static in Java?

link 0

The answer to this question is both Yes and No, depending on whether you are talking about a top level class or a nested class in Java. You cannot make a top level class static in Java, the compiler will not allow it, but you can make a nested class static in Java. A top level class is a class which is not inside another class. It may or may not be public i.e. you can have more than one class in a Java source file and only needs to be public, whose name must be same as the name of the file, rest of the class or interface on that file may or may not be public. On the other hand, a nested class is a class inside a top level class. It is also known as the inner class or member class in Java.

Now, let’s think about what is the meaning of static class, why would someone want to make a class static in Java? If you are familiar with concept of static method and static variable in Java, then you know that anything static can be accessed without creating instance of the class.

For example, you can access the static variable directly as ClassName.variable and you can invoke the static method as ClassName.staticMethod(), this is a great convenience for calling utility method or accessing constants.

This convenience is the main reason Java programmers like to declare nested class as static in Java. Remember, A nested class, if it’s not static then you can’t create its instance without first creating an instance of the outer class, which is a bit inconvenient. Such classes are known as Inner class and they are always associated with an instance of outer class.

We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at  http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

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

Skip to toolbar