java中的静态方法

/*
    1. 被static修饰的成员,称之为类成员,在对象创建之前就存在于方法区中静态区
    2. 被static修饰的成员,可以通过类名直接访问使用,非静态的成员必须要通过对象去调用
    3. static可以修饰成员变量和成员方法
    4. 非静态的成员方法既可以访问静态的成员[变量或方法],也可以访问非静态的成员[变量或方法]
    5. 静态的成员方法只能访问静态的成员[变量或方法]
    6. 静态的成员方法不能使用this关键字的

 */

1.static不仅可以修饰成员变量也可以修饰成员方法

```plaintext
class Demo7{
    int a = 10;
    static int b = 20;
}
```
public static void show2(){
        System.out.println("这是静态的成员方法");
    }

2.被static修饰的成员,可以通过类名直接访问使用,非静态的成员必须要通过对象去调用

class shuzi {
    int a;
    static int b;

    public shuzi() {

    }

    public shuzi(int a, int b) {
        this.a = a;
        this.b = b;
    }


    //非静态的方法:
    public int fun1() {
        int x=a*b;

        return x;//非静态的方法可以调用静态或者是非静态的成员方法和成员变量
    }
    //静态的方法:
    public static void fun2() {
//        int c=a*b;   //静态的方法只能调用静态的成员变量和方法
        System.out.println(b);
    }

}


public class StaticDemo {
    public static void main(String[] args) {
        shuzi s1 = new shuzi(3,5);
        System.out.println(s1.fun1());
        s1.fun2();                 //不建议这样写,可以直接使用类名去调用其中的静态方法
        shuzi.fun2();              //一个类中的所有静态方法都可以直接使用类名去调用

        s1.fun1();                 //非静态的成员需要通过对象来进行调用
        System.out.println(s1.a);  //非静态的成员变量
    }
}
  1. 非静态的成员方法既可以访问静态的成员[变量或方法],也可以访问非静态的成员[变量或方法]
public int fun1() {
        int x=a*b;
        return x;//非静态的方法可以调用静态或者是非静态的成员方法和成员变量
    }

静态的成员方法只能访问静态的成员变量和方法

public static void fun2() {
//        int c=a*b;   //静态的方法只能调用静态的成员变量和方法
        System.out.println(b);
    }
posted @ 2024-09-24 13:26  你的镁偷走了我的锌  阅读(32)  评论(0)    收藏  举报