2022.3.29 static
package com.oop.demo09;
?
//static
public class Student {
private static int age;//静态变量 类变量 通常使用类名调用
private double score;//非静态变量
?
public static void main(String[] args) {
Student student = new Student();
//通过对象名.变量名调用
System.out.println(student.score);
System.out.println(student.age);
?
//通过类名.变量名调用 所有也叫类变量
System.out.println(Student.age);
//System.out.println(Student.score);非静态变量不可以通过类名调用
}
}
?
静态方法
package com.oop.demo09;
?
import sun.misc.PostVMInitHook;
?
//static
public class Student {
//非静态方法
public void run(){
?
}
//静态方法
public static void go(){
?
}
public static void main(String[] args) {
//静态方法通过类名.方法名调用,(调用另一个类中的静态方法同理)
Student.go();
?
//静态方法还可以直接调用:因为这个静态方法在这个类中
go();
?
//非静态方法,无法通过类名.方法名调用,通过对象名.方法名调用
Student student = new Student();//实例化这个类new
student.run();
new Student().run();//还可以这样直接调用
?
student.go();//静态方法也可以通过对象名.方法名调用
?
}
?
}
?
package com.oop;
?
public class Demo01 {
public static void main(String[] args) {
//静态方法static,通过类名.方法名调用(调用另一个类中的方法同理)
Student.say();
?
Student student = new Student();
student.say1();
?
new Student().say1();
}
//两个非静态方法可以调用
public void a() {
b();
}
public void b() {
}
//两个静态方法可以调用
public static void a1() {
b1();
}
public static void b1() {
}
?
//一个非静态一个静态可以调用
public void a3() {
b3();
}
public static void b3() {
}
?
/*一个静态一个非静态不可以调用
public static void a2() {//和类一起加载
b2();
}
public void b2() {//实例化之后才存在
}*/
}
?
package com.oop;
?
//学生类
public class Student {
//静态方法
public static void say() {
System.out.println("学生说话");
}
//非静态方法
public void say1() {
System.out.println("学生又说话");
}
}
静态导入包
package com.oop.demo09;
?
//import java.lang.Math;一般这么导入类就行了
?
//静态导入包 直接导入方法 作为了解
import static java.lang.Math.random;
import static java.lang.Math.PI;//导入PI
?
public class Test {
public static void main(String[] args) {
System.out.println(random());//不用写Math.random();
System.out.println(PI);
}
}
?