【问题标题】:How a static method call works in Java?Java 中的静态方法调用是如何工作的?
【发布时间】:2020-09-23 12:14:44
【问题描述】:

当调用函数testFunc()时,我没有使用语法 Apples.testFunc()。然而代码运行成功。怎么样?

class Apples {

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

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

【问题讨论】:

  • 整个班级都可以访问同一班级的私人成员。

标签: java static static-methods


【解决方案1】:

当为类分配内存时,静态方法或静态变量在类内分配内存。所以我们可以使用类名访问静态成员函数或数据变量。 我们可以如下调用静态函数

class Main1 {

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

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

class Main1 {

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

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

答案是一样的,但是当静态函数在其他类中时,我们必须使用类名来调用它

【讨论】:

    【解决方案2】:

    因为,静态方法在同一个类中。所以,你不需要指定类名。

    如果是不同的类,则需要指定类名。

    记住: 非静态方法可以访问静态和非静态成员,而静态方法只能访问静态成员。

    例如:

    调用不同类中的静态方法,你需要这样做:

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

    【讨论】:

      【解决方案3】:

      您的函数 testFunc() 与函数 main 位于同一类中。所以你不需要在函数 testFunc() 之前使用类名。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-21
        相关资源
        最近更新 更多