Static Method & Final

Static Method:-

  • public class Vehicle{
           public static void horn(){
                  System.out.println("horn");
         }
    }
  • Now the horn method can be called without creating an object.
  • public class Myclass{
         public static void main(String args[]){
               Vehicle.horn();  //calling horn() method without creating object of class Vehicle.
       }
    }
  • Another Example of static methods are those of Math class , which is why you can call them without creating a Math Object.
  • Also main method must always be static.

Final:-

  • Use the final keyword to mark a variable constant , so that it can be assigned only onces.
  • class Myclass{
           public static final double PI = 3.14;
           public static void main(String args[]){
                System.out.println(PI);
       }
    }
  • Now PI is constant.Any attempt to assign it’s value will cause an error.
  • Note- Method & classes can also be marked final.This will serves to restrict methods so that they can’t be overridden & classes so that they can’t be made subclasses.