When will you define method static

When will you define method static

Answer : Whenever you want your method to be access on class level. You could define static method with static key word and this specifics that method belongs to class level not a with a instance of the class.

Methods declared static has below restriction:

  • They can only call other static methods.
  • They must only access static data.
  • They cannot refer to this or super in any way.
  • They can be accessed directly using class and don’t instance of class to access it

Example:

package com.javahonk.staticTest;

public class StaticTest {

    public static void main(String args[]) {
	methodTest();
    }

    private static void methodTest() {
	System.out.println("Method is static and "
		+ "don't need class instance to access it.");
    }

}

 

Leave a Reply

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

I am not Robot *