'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 1:[1]
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!");
}
}
Solution 2:[2]
Your function testFunc() is in same class where the function main is. So you don't need to use class name before function testFunc().
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Preeti |
Solution 3 | sarwadnya deshpande |