Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a static method call works in Java?

When calling out the function testFunc(), I am not using the syntax Apples.testFunc(). Yet the code runs successfully. How so?

class Apples {
      
       public static void main(String args[] ) {
           testFunc();
       }   
       
       public static void testFunc() {
           System.out.println("Hello world!");
       }
    }
   
like image 634
akshayKhanapuri Avatar asked Jun 04 '20 13:06

akshayKhanapuri


3 Answers

Since, the static method is in the same class. So, you don't need to specify the class name.

If it is in different class, then you need to specify the class name.

Remember: Non-static methods can access both static and non-static members whereas static methods can access only static members.

For example :

Calling a static method present in different class, you need to do like this :

import com.example.Test;

public class Apples {

   public static void main(String args[]) {
      Test.testFunc();
   }   
}

package com.example;

public class Test {

   public static void testFunc() {
      System.out.println("Hello world!");
   }

}
like image 175
Anish B. Avatar answered Oct 24 '22 00:10

Anish B.


Your function testFunc() is in same class where the function main is. So you don't need to use class name before function testFunc().

like image 22
Preeti Avatar answered Oct 23 '22 23:10

Preeti


When the memory is allocated for the class, Static method or static variable is assigned memory within a class. So we can access static member function or data variable using class name. we can call static function as below

class Main1 {

    public static void main(String args[] ) {
        Main1.testFunc();
    }   

    public static void testFunc() {
        System.out.println("Hello world!");
    }
 }

or

class Main1 {

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

    public static void testFunc() {
        System.out.println("Hello world!");
    }
 }

the answer will be same, but when static function is in other class then we must use classname to call it

like image 34
sarwadnya deshpande Avatar answered Oct 24 '22 01:10

sarwadnya deshpande