为什么我不能有实例成员在一个静态类,但我能有实例成员的静态方法?能有、静态、实例、成员

2023-09-05 03:43:36 作者:一个人哭泣在夜里。

我们知道,如果一个类是由静态的,所有的类中的成员必须是静态的;不可能有内部静态类的任何实例成员。如果我们试图做到这一点,我们得到一个编译时错误。

但是,如果有一个静态方法里面一个实例成员,我没有得到一个编译时错误。

 公共静态类MyStaticClass
    {
        //不能做到这一点
        // INT I;

        //可以做到这一点,虽然。
        静态无效MyStaticMethod()
        {
            诠释J;
        }
    }
 

解决方案

静态方法和属性不能访问非静态字段和事件在其包含的类型,而不能访问任何对象的实例变量,除非它被明确地传递方法参数。

 公共类MyStaticClass
{
    静态诠释J; //静态成员
    INT I; //实例成员
    静态无效MyStaticMethod()
    {
        I = 0; //你不能访问
        J = 0; //你可以访问
    }
}
 
JavaSE 面向对象01

We know that If a class is made static, all the members inside the class have to be static; there cannot be any instance members inside a static class. If we try to do that, we get a compile time error.

But if have an instance member inside a static method, I do not get a compile time error.

    public static class MyStaticClass
    {
        // cannot do this
        //int i;

        // can do this though.
        static void MyStaticMethod()
        {
            int j;
        }
    }

解决方案

Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

public class MyStaticClass
{
    static int j; //static member
    int i;//instance member
    static void MyStaticMethod()
    {
        i = 0; // you can't access that
        j = 0; // you can access 
    }
}