Search code examples
javastaticstatic-methods

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

Solution

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