Skip to content
APPCITORThe Tech Blog
Esc

Java OOP – Static variables and methods

August 8, 2020 2 min read

Java OOP – Static variables and methods

All the static members are created in the template and we can access them without an object. Non-static variables and methods cannot access without an object. Static members are common for all the instances(objects) of the class but non-static members are separate for each instance of class. Today we are going to talk about static variables and the methods. Also you will learn about static initializer and object initializer later in this article.

Static Variables

Here variable x is an instance variable and y is a static variable. When you assigning the values for x, they would print as 1, 10, 100 to the given order. But y is common for all the objects as it is static. So when you assign 2 first and then you assign 20, 2 is replacing to 20 and then to 200 as given in the program. They would not store separately. Therefore the output is,

Static Methods

Here the illegal statement is because “m1()” is not static. You already know non-static methods are not running without an object. So we can create an object and call the “m1()” method by the object reference. “m2()” method is running because it is static and it can access without object. Without running the illegal statement output will come as,

Static Initializer:

Java provides a feature called a static initializer that’s designed specifically to let you initialize static fields.

In static initialization, first the values are assigning to the variables declared in the program. Then the static block will execute. Here the static block is running automatically. Let’s see an example.

When “MyClass” template is taking to the ram from the hard, the static initializer starts to run. Therefore static blocks are start to run from top to bottom of the program automatically. And after that the main method will run.

Output:

Object Initializer:

When the template is loaded and asking for a new object, it will create a new object and inside the object will create attributes and methods. This is the object initialization.

In object initialization, first the declared values are assigning and then the instance blocks are executing. At last the constructor will execute. Let’s see an example.

Static initializer is running only once. Even the object initializer runs two times, static initializer not runs more than one time.

Here both instance blocks will run to the order first and at last the constructor will run.

Output:

Guys, I hope you all got knowledge about static variables, methods and also Initializers. The next few articles will teach you about the basic Principles of OOP. Let’s start it with “Inheritance”.

Thank you.

Share this article

Keep reading