Java Static & Final

static & final in java

Quick Links


Static:

When you declare a variable or a method as Java Static & Final, it belongs to the class, rather than to a specific instance. This means that only one instance of a static member exists, even if you create multiple objects of the class, or if you don’t create any. It will be shared by all objects.

Example :

                    public class Counter {
  public static int COUNT=0;
  Counter() {
    COUNT++;
  }
}

The same concept applies to static methods.

                    public class Vehicle {
  public static void horn() {
    System.out.println(“Beep”);
  }
}

Also, the main method must always be static.


Final:

Use the final keyword to mark a variable constant, so that it can be assigned only once.

Example :

                    class MyClass {
  public static final double PI = 3.14;
  public static void main(String[ ] args) {
    System.out.println(PI);
  }
}

Methods and classes can also be marked final. This serves to restrict methods so that they can’t be overridden and classes so that they can’t be subclassed.


Spread the love

Leave a Comment

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