Java static静态方法示例、限制、为什么main方法是静态的

如果在任何方法上应用static关键字,此方法称为静态方法。(更多教程请阅读码农之家)

  • 静态方法属于类,而不属于类的对象。
  • 可以直接调用静态方法,而无需创建类的实例。
  • 静态方法可以访问静态数据成员,并可以更改静态数据成员的值。

静态方法的示例

//Program of changing the common property of all objects(static field).  

class Student9 {
    int rollno;
    String name;
    static String college = "ITS";

    static void change() {
        college = "BBDIT";
    }

    Student9(int r, String n) {
        rollno = r;
        name = n;
    }

    void display() {
        System.out.println(rollno + " " + name + " " + college);
    }

    public static void main(String args[]) {
        Student9.change();

        Student9 s1 = new Student9(111, "Karan");
        Student9 s2 = new Student9(222, "Aryan");
        Student9 s3 = new Student9(333, "Sonoo");

        s1.display();
        s2.display();
        s3.display();
    }
}

上面代码执行输出以下结果 -

111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

执行正常计算的静态方法的另一个示例:

//Program to get cube of a given number by static method  

class Calculate {
    static int cube(int x) {
        return x * x * x;
    }

    public static void main(String args[]) {
        int result = Calculate.cube(5);
        System.out.println(result);
    }
}

上面代码执行输出以下结果 -

125

静态方法的限制

静态方法有两个主要限制。它们分别是:

  • 静态方法不能直接使用非静态数据成员或调用非静态方法。
  • thissuper两个关键字不能在静态上下文中使用。
class A {
    int a = 40;// non static

    public static void main(String args[]) {
        System.out.println(a);
    }
}

上面代码执行输出以下结果 -

[编译错误!]Compile Time Error

为什么java main方法是静态的?

这是因为对象不需要调用静态方法,如果它是非静态方法,jvm首先要创建对象,然后调用main()方法,这将导致额外的内存分配的问题。

posted @ 2021-12-15 18:35  small_123  阅读(154)  评论(0编辑  收藏  举报