Java Instance and Static Methods

In this lesson, you will learn the differences between the Java Instance and Static methods.

Instance Method in Java

The instance method in Java is object-related and requires an object of its class to be created before being called.
So, to call an instance method, we must first instantiate the class/create an object of a class, and then we can call the desired method using that object.

Example:

class Test {
    
  public void print(String word) {
    System.out.println(word);
  }
}

class Test2 {
    
  public void callPrintMethod() {
    Test test = new Test();
    test.print("Hello");
  }
}

Here we have declared the print method, and in the main method, we first created an object of class Test, and using the object reference test we called the method.


Static method in Java

The static method in Java is tied to the class itself, not to the object. It is called via the class name (ClassName.methodName(…)). We do not have to create an object of that class.

Static methods can not be overridden, and also, can’t access instance methods and instance variables.

Example:

class Test {
    
  public static void print(String word) {
    System.out.println(word);
  }
    
  public static void main(String[] args) {
    print("Hello!"); // OK
    Test.print("Hello!"); // OK
  }
}
class Test2 {
    
  public static void main(String[] args) {
    Test.print("Hello!"); // OK
  }
}

In the above example, we declared the print method with a static keyword to access it without creating an object. You can see that we called the print method in two ways. If we want to call it within the same class in which the method is declared, we can do so without and with the class name.

In the Test2 class, we had to call the method via the class name because the print method belongs to the Test class.

Example 2:

class Test {
    
  String hello = "Hello!";
    
  public static void main(String[] args) {
    String h = hello; // DOES NOT COMPILE
  }
}

Here we tried to access the instance variable within the static method, and this will not compile because as we said static methods can not access instance methods and variables.
So we get:
“Non-static field ‘hello’ cannot be referenced from a static context.”

We can only access it if we create an object of that class:

class Test {
    
  String hello = "Hello!";
  
  public static void print(String word) {
    System.out.println(word);
  }
    
  public static void main(String[] args) {
    Test test = new Test();
    String h = test.hello; // DOES COMPILE
  }
}


This was all about Instance and Static methods in Java! Proceed to the next lesson.

 Happy Learning!

Leave a Reply

Your email address will not be published.