1.static简介
(1)特点:
1、static是一个修饰符,用于修饰成员。(成员变量,成员函数)static修饰的成员变量 称之为静态变量或类变量。
2、static修饰的成员被所有的对象共享。
3、static优先于对象存在,因为static的成员随着类的加载就已经存在。
4、static修饰的成员多了一种调用方式,可以直接被类名所调用,(类名.静态成员)。
5、static修饰的数据是共享数据,对象中的存储的是特有的数据。
(2)成员变量和静态变量的区别:
1、生命周期的不同:
成员变量随着对象的创建而存在随着对象的回收而释放。
静态变量随着类的加载而存在随着类的消失而消失。
2、调用方式不同:
成员变量只能被对象调用。
静态变量可以被对象调用,也可以用类名调用。(推荐用类名调用)
3、别名不同:
成员变量也称为实例变量。
静态变量称为类变量。
4、数据存储位置不同:
成员变量数据存储在堆内存的对象中,所以也叫对象的特有数据。
静态变量数据存储在方法区(共享数据区)的静态区,所以也叫对象的共享数据。
(3)静态使用时需要注意的事项:
1、静态方法只能访问静态成员。(非静态既可以访问静态,又可以访问非静态)
2、静态方法中不可以使用this或者super关键字。
3、主函数是静态的
2.static例子
2.1 第一种
public class Son extends Father{
{
System.out.println("son_no_static");
}
static{
System.out.println("son_static");
}
public Son() {
System.out.println("son_constructor");
}
public static void main(String[] args) {
//直接运行main,不创建对象
}
}
class Father{
{
System.out.println("father_no_static");
}
static{
System.out.println("father_static");
}
public Father() {
System.out.println("father_constructor");
}
}
- 输出
father_static
son_static
2.2 第二种
public class Son extends Father{
public static void main(String[] args) {
Son son = new Son();
}
}
}
- 输出
father_static
son_static
father_no_static
father_constructor
son_no_static
son_constructor
2.3 第三种
public class Son extends Father{
public static void main(String[] args) {
Son son = new Son();
Son son1 = new Son();
}
}
- 输出
father_static
son_static
father_no_static
father_constructor
son_no_static
son_constructor
father_no_static
father_constructor
son_no_static
son_constructor