Java 中的 static 使用之静态方法

与静态变量一样,我们也可以使用 static 修饰方法,称为静态方法或类方法。其实之前我们一直写的 main 方法就是静态方法。静态方法的使用如:

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、 静态方法中可以直接调用同类中的静态成员,但不能直接调用非静态成员。如:

public class Helloworld {
    String name="离歌笑";//非静态变量name
    static String hobby="conqueror";//静态变量hobby

    //在静态方法调用非静态变量
    public static void print(){
        System.out.println("欢迎你!"+name);//不能直接调用非静态变量
        System.out.println("爱好:"+hobby);//可以直接调用静态变量
    }
}

如果希望在静态方法中调用非静态变量,可以通过创建类的对象,然后通过对象来访问非静态变量。如:

//在静态方法中调用非静态变量
public static void print(){
//创建类的对象
Helloworld hello=new Helloworld();
//通过对象来实现在静态方法中调用静态变量
System.out.println("欢迎你!"+hello.name);
System.out.println("爱好:"+hobby);
}

2、 在普通成员方法中,则可以直接访问同类的非静态变量和静态变量,如下所示:

String name="离歌笑";//非静态变量name
static String hobby="conqueror";//静态变量hobby

//普通成员方法可以直接访问非静态变量和静态变量
public void show(){
System.outprintln("欢迎你”+name);
System.outprintln("爱好”+hobby)
}
}

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

//普通成员方法
public void show(){
System.out.prinln(“Welcome to mooc”);
}
//静态方法
public static void print (){
System.out.println("欢迎来到慕课”);
}
public static void main(String [] args)
{
    //普通成员方法必须通过对象来调用
    Helloworld hello=new Helloworld();
    hello.show();
    //可以直接调用静态方法
    print();
    }

猜你喜欢

转载自blog.csdn.net/qq_37999723/article/details/78175983