What is the static modifier in Java?

What is static modifier in Java?

What is the static modifier in Java?

What is the static modifier in Java?
  • Static is a modifier applicable to methods and variables but not for classes.
  • You can think of a ‘static’ method or field as if it were declared outside the class definition. In other words, there is only one ‘copy’ of a static field/method. Static fields/methods cannot access non-static fields/methods.
  • We can’t declare a top-level class with static modifier but we can declare the inner class as static(such type of inner are called static nested classes).
  • In the case of instance variables for every object a separate copy will be created but in the case of static variable a single copy will be created at the class level and shared by every object of that class.
package com.java4us;

class Test {
    static int x = 10;
    int y = 20;

    public static void main(String args[]) {
        Test t1 = new Test();
        t1.x = 100;
        t1.y = 200;
        System.out.println(t1.x + "..." + t1.y); // 100...200
        Test t2 = new Test();
        System.out.println(t2.x + ".." + t2.y); // 100..20
    }
}
  • We can’t access instance member directly from the static area but we can access from instance area directly.
  • We can access static members from both instances and the static area directly.
  • For static method overloading and inheritance, concepts are applicable but overriding concepts are not applicable but instead of overriding method hiding concepts are applicable.

Leave a Reply

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

*