Static keyword in Java

In Java, variables, which are declared with the static keyword, belong to the class, not to the instance of the class. This means that we do not need to initialize objects to use variables that are declared with the static keyword in those classes.

For example, we have the following class:

In the Example class above, I declared NAME to be static. Then, I do not need to initialize the object for the Example class, but I still print out the value of NAME.

Result:

Static keyword in Java

For the same approach, suppose you define a static method in the Example class as follows:

As you can see, you do not need to initialize the Example object, but you can also call the sum() static method.

Result:

Static keyword in Java

Static variables can be declared in normal classes, abstract classes, or interface classes.

But for methods from Java 7 and earlier, we can only declare static methods in normal classes or abstract classes. If declared in the interface will be prompted error.

For example:

Static keyword in Java

From Java 8, Java has allowed us to declare static methods in our interface class.

For example:

Static keyword in Java

When you run you will also see the results as above.

 

Static keyword in Java
Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
5Share on Google+
Google+
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

One thought on “Static keyword in Java

  1. The static keyword can be used with the variables, blocks, methods, imports and nested classes. A static variable is common to all objects of the class unlike normal variable.

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.