static使用之静态方法

  public class HelloWorld{

  // 使用static 关键字声明静态方法

  public static void print(){

     System.out.println("欢迎你");

}

    public static void main(String[] args){

 //使用类名调用静态方法

    HelloWorld.print();

 //使用对象名调用静态方法   

 HelloWorld demo = new HelloWorld ();

demo.print( );

    }

}

需要注意:

1.静态方法中可以直接调用同类的静态成员,不能直接调用非静态成员。如果希望在静态方法中调用非静态变量,可以通过创建类的对象,然后通过对象访问非静态变量。

2.在普通成员方法中,可以直接访问同类的静态变量和非静态变量。

3.静态方法中不能直接调用非静态方法,需要通过对象来访问非静态方法。

原文地址:https://www.cnblogs.com/Dantewuxin/p/5693960.html