Java SE
static
静态成员变量VS实例成员变量
静态成员变量(类变量) 有static 修饰 属于类,所有对象共有,在计算机中只有一份,调用方法 类名.静态变量
实例成员变量(对象的变量)属于对象的变量
public class Student {
// 静态成员变量,static修饰,属于类,所有对象共享,在计算机内存中只存在一份
static String name;
//实例成员变量,无static修饰,属于对象,对象的变量
int age;
}
/**
* 类名.静态变量
* 对象.实例变量
* 对象.静态变量(不推荐)
* @param args
*/
public static void main(String[] args) {
Student s1=new Student();
s1.name="张三";
s1.age=23;
System.out.println(s1.name);
System.out.println(s1.age);
Student s2=new Student();
s2.name="李四";
s2.age=24;
System.out.println(s2.name);
System.out.println(s2.age);
System.out.println(Student.name);
}
public class User {
public static int num;
public User(){
User.num++;
}
}
public static void main(String[] args) {
new User();
new User();
new User();
System.out.println(User.num);
}
- 1.类变量:属于类,在内存中只有一份,用类名调用
- 2.实例变量:属于对象,每一个对象都有一份,用对象调用
静态方法VS实例方法
public class Student {
double score;
//static修饰的方法,可以通过类名直接调用,不需要创建对象
public static void printHelloWorld(){
System.out.println("Hello World");
}
//实例方法,需要通过对象调用
public void isPass(){
System.out.println(score>=60?"通过":"未通过");
}
}
public static void main(String[] args) {
Student.printHelloWorld();
Student s = new Student();
s.score=90;
s.isPass();
}
类方法的知识应用
public class RandomCodeUtil {
//私有化构造器, 防止外部创建对象
private RandomCodeUtil(){}
public static String getRandomCode(int length) {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
String res = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
res+=chars.charAt(random.nextInt(chars.length()));
}
return res;
}
}
- 工具类需要私有化构造器,防止外部创建对象
static 注意事项
类方法可以直接访问类变量,不可以直接访问实例变量,不可以出现this
实例方法可以直接访问类变量,也可以直接访问实例变量,可以出现this
public class Student {
static String name;
double score;
public static void fn01(){
//类方法可以直接访问类变量,不可以直接访问实例变量,不可以出现this
System.out.println(name);
//System.out.println(score);
//System.out.println(this);
}
public void fn02(){
//实例方法可以直接访问类变量,也可以直接访问实例变量,可以出现this
System.out.println(name);
System.out.println(score);
System.out.println(this);
}
static 代码块
类加时自动加载,由于类只加载一次,静态代码块也只执行一次
public class Student {
static int num = 100;
static String name = "张三";
static{
System.out.println("静态代码块");
}
}
实例代码块
每次创建实例对象时都会执行实例代码块,而且在构造器之前执行
public class Student {
int age=100;
//实例代码块
{
System.out.println("Student 类的构造代码块执行了");
System.out.println(age);
}
public Student(){
System.out.println("Student 类的无参构造方法执行了");
}
public Student(int age){
this.age=age;
System.out.println("Student 类的有参构造方法执行了");
}
}
单例模式
饿汉单例
public class A {
public static A a=new A();
private A(){};
public static A getInstance(){
return a;
}
}
懒汉单例
public class B {
private static B b;
private B(){};
public static B getInstance(){
if(b==null){
b=new B();
}
return b;
}
}
注意私有化构造器
super()和this()
访问本类成员:
this.成员变量 //访问本类成员变量
this.成员方法 //调用本类成员方法
this() //调用本类空参数构造器
this(参数) //调用本类有参数构造器
访问父类成员:
super.成员变量 //访问父类成员变量
super.成员方法 //调用父类成员方法
super() //调用父类空参数构造器
super(参数) //调用父类有参数构造器
注意:this和super访问构造方法,只能用到构造方法的第一句,否则会报错。