java中的静态方法 [英] Static method in java

查看:107
本文介绍了java中的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说静态方法应该只在java中使用静态变量。
但是,main方法也是静态的,对吧?

I heard that static methods should use only static variables in java. But, main method is also static, right?

推荐答案

您的问题:声明静态方法应该只使用静态变量是否正确?

Your question: is the statement " static methods should use only static variables" correct?

没有。该陈述不正确。

正确的陈述将是静态方法只能使用那些定义为静态的实例变量

The correct statement will be "static methods can only use those instance variables that are defined static"

查看以下代码并阅读评论:

Take a look at following code and read the comments:

Class A{
    int i;
    static int j;

    public static void methodA(){
        i = 5; //cannot use since i is not static
        j = 2; //can use.

        int k = 3; //k is local variable and can be used no problem

        **EDIT:**//if you want to access i
        A a = new A();
        //A.i = 5; //can use.  
        a.i = 5; // it should be non-capital "a" right?
    }
}

这篇关于java中的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆