简体   繁体   中英

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!");
       }
    }
   

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!");
   }

}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM