Java static关键字详解 -16天 学习笔记

static

package com.oop.Demo06;
//static
public class Student {
    
    

    private static int age;  //静态的变量  多线程
    private String name;  //非静态的变量

    public void run(){
    
    
        System.out.println("pao");
        go();//非静态方法可以调用静态方法

    }

    public static void go (){
    
    
        System.out.println("qu");
    }

    public static void main(String[] args) {
    
    
        Student s1 = new Student();
        //s1.name.sout快捷键
        System.out.println(s1.name);
        System.out.println(s1.age);
        System.out.println(Student.age);
     // System.out.println(Student.name); 报错因为非静态不能这样使用
        //所以有静态变量我们一般使用类名去调用

        System.out.println("=============");
        Student.go();//静态可以通过类名加方法调用甚至可以之间使用方法名
             go();


    }

}
package com.oop.Demo06;

public class Person {
    
    
    //假如Person被final修饰了,Student就不能继承
    //final之后断子绝孙

    {
    
    
        //代码块()匿名代码块,不建议这样写
        System.out.println("匿名代码块");
    }

    static {
    
    
        //静态代码块,永久且只执行一次
        System.out.println("静态代码块");

    }
    public Person(){
    
    
        System.out.println("无参构造器(构造方法)");
    }

    public static void main(String[] args) {
    
    
        Person p1 = new Person();
        //输出  静态代码块
        //     匿名代码块
        //     无参构造器(构造方法)

        Person p2 = new Person();
         // 只有两个是因为静态代码块只会运行一次
        //   输出   匿名代码块
        //     无参构造器(构造方法)

    }
}
package com.oop.Demo06;

//import static java.lang.Math.rondom;
//import static java.lang.Math.Pi;

public class Text {
    public static void main(String[] args) {
        System.out.println(Math.random());//Math类,可以导入包之后就不用在写Math
        System.out.println();
    }
}

猜你喜欢

转载自blog.csdn.net/yibai_/article/details/114903148