面向对象——static关键字详解
static关键字:
- static关键字修饰的属性和方法放在静态存储区
- 静态方法和静态属性是和类一起加载的(最早加载的)
- 静态方法只能调用静态方法/属性,不能调用非静态方法/属性(静态方法加载时,非静态方法还未加载完成)
- 非静态方法可以调用静态方法/属性
final关键字::如果这个类被final定义了,其他的类就不能继承此类了!!!
package(包)com.du.OOP.demo07:类Person(static关键字详解)
package com.du.OOP.demo07;
//如果这个类被final定义了,其他的类就不能继承此类了!!!
public final class Person {
//赋初始值
{
System.out.println("匿名代码块");//代码块(匿名代码块)
}
//只执行一次
static{
System.out.println("静态代码块");//静态代码块
}
public Person() {
System.out.println("构造方法");
}
public static void main(String[] args) {
Person person1 = new Person();//1.打印:静态代码块 2.打印:匿名代码块 3.打印:构造方法
Person person2 = new Person();//1.打印:匿名代码块 2.打印:构造方法
//由此可以得出结论:静态代码块只执行一次!!!
}
}
package(包)com.du.OOP.demo07:类Student(static关键字详解)
package com.du.OOP.demo07;
//static
public class Student {
private static int age;//静态变量
private double score;//非静态变量
public void run(){
System.out.println("run!");
go();//合法,非静态方法可以调用静态方法
}
public static void go(){
System.out.println("go!");
//run();//报错,不合法,静态方法只能调用静态方法,不能调用非静态方法
}
//main()方法也是static方法!!!
public static void main(String[] args) {
Student s1 = new Student();
//static属性
System.out.println(Student.age);//直接用Student类调属性
//System.out.println(Student.score);//报错:score不是在静态字段
System.out.println(s1.age);//通过实例对象s1调属性
System.out.println(s1.score);
//static方法
//Student.run();//报错,无法直接调用,必须先将Student进行实例化
//run();//同样报错
new Student().run();
Student.go();//go()静态方法可以直接调,
go();//可以正常调用
}
}
package(包)com.du.OOP.demo07:类Test(static关键字详解)
package com.du.OOP.demo07;
import static java.lang.Math.random;
public class Test {
public static void main(String[] args) {
System.out.println(Math.random());//如果想直接调用random()方法,则可以导入这个方法:import static java.lang.Math.random;注:必须使用static关键字
}
}