static关键字
本片要点
静态变量最好用类来调用
静态变量对于类,所有对象(实例)所共享,当直接使用类去调用得到说明这个变量是静态的。
加了static就是从属于这个类,其他人用不了,只有本类能用。
static修饰的含义隶属于类,而不是对象,是一个公共的存储内存空间。
有final的方法不可被继承。 (—。—)断子绝孙 常量修饰符
代码
package com.oop.demo07;
//static :
public class Student {
private static int age;//静态变量 多线程会用到
private double score;//非静态变量
public void run(){
go();//非静态的方法可以调用静态的方法东西
}
public static void go(){
}
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(s1.score);
System.out.println(s1.age);
System.out.println(Student.age);
new Student().run();//没有static要先new
Student.go();//有static可以这样直接调
go();//有static还可以这样调
}
}
package com.oop.demo07;
public class Person {
//第二个执行 可用于赋初值~
{
//代码块(匿名代码块)
System.out.println("匿名代码块");
}
//第一个执行 只执行一次
static{
//静态代码块
System.out.println("静态代码块");
}
//第三个执行
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;
public class Test {
public static void main(String[] args) {
System.out.println(Math.random());
System.out.println(random());//导入包后可以不要Math
}
}
//假设Person类变成这样
public final class Person{}
//那么Student类想继承Person类就不可以