静态变量和非静态变量
静态变量可以直接通过类来进行调用,而非静态变量不能直接通过类进行调用
静态方法和非静态方法
静态方法可以直接用 Student.go();来执行甚至可以直接用go();
但是非静态方法只能通过new 新对象后用对象来执行
而且非静态方法里面可以直接调用静态方法里面的东西
而静态方法里面只能调用静态方法的类容,不能调用非静态方法的类容
主要原因是: 静态方法和类一起加载。
package oop.gdw.demo07;
public class Student {
public static int age;
public double score;
public static void main(String[] args) {
Student s1 = new Student();
System.out.println(Student.age);
//System.out.println(Student.score);
System.out.println(s1.age);
System.out.println(s1.score);
Student.go();
//Student.say();
Student student = new Student();
student.say();
}
public static void go(){
System.out.println(1);
}
public void say(){
System.out.println(2);
}
}
匿名代码块,是在Student这个对象创建的时候就创建了(在构造器之前)
{
}
静态代码块,是在类加载的时候就执行,且只执行一次(最先执行)
static{
}
package oop.gdw.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();
}
}
运行结果:
网上定义:
匿名代码块 :即类的 代码块,每次创建对象时会在构造方法之前执行唯一的一次 2. 静态代码块 静态代码块 :即类的 静态代码块,是和类一起加载到内存的,即比构造方法先执行的同时还要比 匿名代码块 先执行,且只执行唯一的一次。
静态导入包!
package oop.gdw.demo07;
import static java.lang.Math.random;//静态导入包
public class Test {
public static void main(String[] args) {
System.out.println(random());
}
}
主要是能直接用random()方法
不需要像Math.random()这样调用
final 修饰类的不能继承
final 之后断子绝孙