static关键字详解
1、知识点都在代码注释中,便于理解
`package oop.Demon09;
import oop.Demon05.Students;
public class Student {
private static int age=10;//静态变量 多线程
private double score;//非静态变量
public void run(){
System.out.println("run");
//非静态方法 可以直接访问 该类中的静态方法
go();
}
public static void go(){
System.out.println("go");
//但是 静态方法 只能调用静态方法 因为静态方法 跟类一块加载,加载之前 都没有非静态方法
}
public static void main(String[] args) {
Student s1 = new Student();
// s1.age 可以调用
// Student.age 也可以 用类名.属性名 调用
System.out.println(Student.age);
// System.out.println(Student.score);报错, 类名.属性名 调用 只能用在static类型变量
System.out.println(s1.age);
System.out.println(s1.score);
new Student().run(); //非静态方法,只能先new,在调用
Student.go(); go();//静态方法,直接调用, 类名。方法名 或者 直接 方法名
}
}
2、
package oop.Demon09;
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();
//匿名代码块
//构造方法
}
}
3、
package oop.Demon09;
//静态导入包
import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
public static void main(String[] args) {
System.out.println(Math.random()); //产生一个随机数 每次都不一样
System.out.println(random()); //可以直接 用方法名字
System.out.println(PI);
}
}
4、通过 final修饰的类 不能被继承
还没有评论,来说两句吧...