java中的静态static关键字

类的静态成员函数不能访问非静态的成员函数以及非静态的成员变量,

但是反过来却是成立的。

即:非静态成员函数可以访问静态成员函数和静态成员变量。

这个可以从静态成员的特点来解释,因为静态成员属于类,因此即便是没有类的对象我们也能访问类的静态成员。

但是非静态成员函数由于只能通过类的对象来访问,所以其必须要有对象才行。

那,反证法:

假如,类的静态成员函数可以访问非静态的成员函数:示例代码如下,

class Test
{
    public static int i;
    private int j;
    public static void ff()
    {
        gg();  //静态成员函数不能访问非静态成员函数
        System.out.println("静态成员函数");
    }
    public void gg()
    {
        System.out.println("非静态成员函数");
    }
}

当我们不创建对象,直接使用类名去访问ff()

Test.ff();

这样是错误的,实际上在eclipse中还没编译之前就报错了。

Cannot make a static reference to the non-static method gg() from the type Test

那么static关键字有什么用呢?

我们可以使用static关键字来限制类的对象只能有一个,代码如下:

package testHello;


class Test
{
    private  int i;
    private static Test test = new Test();
    
    private Test(){}
    
    public static Test getTest()  //这里的static关键字不能少,少了就不能访问上面的test成员变量了
    {
        return test;
    }
    
    public void seti(int num)
    {
        i = num;
    }
    
    public int geti()
    {
        return i;
    }
    
}

public class helloWorld
{

    public static void main(String[] args)
    {
        Test t = Test.getTest();
        t.seti(10);
        System.out.println(t.geti());
    }

}