Title

Static的静态常量访问与静态方法调用

Static的静态常量访问与静态方法调用

======================================================================

Static的静态方法调用

package com.tea.Demo07;

public class Student {

    public void run(){  //非静态方法
    }
    public static void go(){  //静态方法
    }

    public static void main(String[] args) {
        Student s1 = new Student();

        Student.go();  //静态方法时,直接用类名调用
        //Student.run(); //会报错,因为run()为非静态方法

        //也可以用具体对象调用
        s1.run();
        s1.go();
    }
}

Static的静态常量访问

package com.tea.Demo07;

public class Student {

    private static int age; //静态常量
    private double score; //非静态常量

    public static void main(String[] args) {
        Student s1 = new Student();

        //还是建议常量为静态常量时,直接用类名访问
        System.out.println(Student.age);
        //System.out.println(Student.score);会报错,因为score为非静态常量

        //也可以用具体对象访问
        System.out.println(s1.age);
        System.out.println(s1.score);

    }
}

======================================================================

static静态代码块

package com.tea.Demo07;

public class Person {

    //2:赋初始值
    {
        //匿名代码块
        System.out.println("匿名代码块");
    }

    //1:最先输出,而且只执行一次
    static {
        //静态代码块
        System.out.println("静态代码块");
    }

    //3
    public Person() {
        System.out.println("构造方法");
    }

    public static void main(String[] args) {
        Person person1 = new Person();
        System.out.println("===================");
        Person person2 = new Person();
    }
}

======================================================================

静态导入包

package com.tea.Demo07;
import static java.lang.Math.random; //静态导入包
import static java.lang.Math.PI; //静态导入包

public class Test {

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

======================================================================

posted @ 2022-10-01 21:11  花里胡哨的渣渣  阅读(65)  评论(0)    收藏  举报