静态修饰符static

使用与不使用的区别

建议少使用静态修饰符

使用

  1. 与类一起加载,只要类被装载进程序中,该方法一起被加载完成。

    使用举例

    //使用静态修饰符
    public class Student
    {
        public static void say()
        {
            System.out.println("hello world!");
            return;
        }
    }
    //调用
    import Student
    '''
        pubilc static void main(String[] args)
    {
        Student.say();
    }
    //预期输出结果
    hello world!

不使用

  1. 当类被实例化以后才能使用该方法。

    使用举例

    //不使用静态修饰符
    public class Student
    {
        public void say()
        {
            System.out.println("hello world!");
            return;
        }
    }
    //调用
    import Student
    '''
        pubilc static void main(String[] args)
    {
        Student student = new Student();
        student.say();
    }
    //预期输出结果
    hello world!

代码块

举例说明

public class code {
    {//代码块
        System.out.println("默认代码块");
    }
    static{//静态代码块
        System.out.println("静态代码块");
    }
    public static void main(String[] args) {
        System.out.println("程序");
        new code();
        System.out.println("--------");
        new code();
    }
}

输出结果

静态代码块
程序
默认代码块


默认代码块