package com.oop.demo07;
/**
* @ClassName: Student
* @Author: 南冥有猫不须铭
* @Date: 2021/4/20-22:13
* @Description: static关键字详解
*/
//static 静态 (属性、方法)
public class Student {
//static修饰属性-->静态属性
private static int age;//静态变量 多线程!
private double score;//非静态变量
//static修饰方法-->静态方法
public void run(){
go();//非静态方法可以直接调用静态方法
}
public static void go(){
//run(); //静态方法可以调用静态方法,但是不能调用普通方法(非静态方法)
}
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);
//run(); //不能直接调用非静态方法
s1.run(); //只能通过 对象.方法 来调用非静态方法 new Student().run();
//Student.run(); //不能通过 类.方法 来调用非静态方法
Student.go(); //可以通过 类.方法 来调用静态方法
go(); //可以直接调用静态方法
}
}
package com.oop.demo07;
/**
* @ClassName: Person
* @Author: 南冥有猫不须铭
* @Date: 2021/4/20-22:51
* @Description: 静态代码块
*/
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.oop.demo07;
//静态导入包~
import static java.lang.Math.random;
import static java.lang.Math.PI;
/**
* @ClassName: Test
* @Author: 南冥有猫不须铭
* @Date: 2021/4/20-23:05
* @Description: 新特性
*/
public class Test {
public static void main(String[] args) {
System.out.println(random()); //可以不用写 Math.random(),直接写random()
System.out.println(PI);
}
} // final 常量修饰符(断子绝孙修饰符):用final修饰后不能被继承,即没有子类