静态变量
概述:
被static修饰的成员变量就是静态变量。静态变量被该类下所有的对象所共享。
对象空间中就没有这个成员变量,存在方法区的静态区。
使用:
获取值:
对象名.属性名【实际开发坚决不用】
类名.属性名
修改值:
对象名.属性名 = 新值【实际开发坚决不用】
类名.属性名 = 新值
代码示例:
Person类:
public class Person {
String name; //姓名
int age; //年龄
static String country; // 国籍
}
测试类:
public class TestPerson {
public static void main(String[] args) {
// 创建对象
Person p1 = new Person();
System.out.println(p1.age);
System.out.println(p1.name);
System.out.println(p1.country);// 坚决不用
System.out.println(Person.country);
p1.name = "张三";
p1.age = 20;
p1.country = "天朝"; // 坚决不用
System.out.println(p1.age);
System.out.println(p1.name);
System.out.println(p1.country);// 坚决不用
Person.country = "TianChao" ;
System.out.println(Person.country);
}
}
静态变量和非静态变量的区别【典型的面试题】
1、内存空间不一致
静态变量:存在于方法区的静态区
非静态变量:
全局变量:堆空间的对象空间中
局部变量:栈空间
2、所属不同:
静态变量:属于类
非静态变量:
全局变量:属于对象
局部变量:属于方法
3、生命周期不同:
静态变量:随着类的加载而加载 随着类的消失而消失
非静态变量:
全局变量:随着对象的创建而创建 随着对象的消失而消失
局部变量:随着方法的执行而创建 随着方法的停止而消失
4、调用方式不同:
静态变量:类名调用
非静态变量:
全局变量:对象调用
局部变量:直接使用
静态方法
概述:
被static修饰的方法就是静态方法 比如:main方法
属于类,被对象共享但是调用不使用对象调用,可以使用类名直接调用
注意事项:
1、只能使用静态资源【静态变量和静态方法】,不能访问外界非静态成员(因为在静态访问非静态的时候,非静态还不存在)
静态方法中没有对象this,所以不能访问非静态成员
2、因为静态先于对象的存在而存在,所以静态方法中不能出现this和super关键字。
3、可以定义非静态的变量,不能定义静态变量
4、非静态方法可以访问静态成员,也可以访问非静态成员
静态方法使用场景
只需要访问静态成员时;
不需要访问对象状态,所需参数都由参数列表显示提供
代码示例:
Person类:
public class Person {
String name;
int age;
static String country;
public void show() {
System.out.println("我是普通的方法");
}
public static void work() {
System.out.println("我是静态方法");
// System.out.println(name);报错 非静态资源
// System.out.println(age);报错 非静态资源
System.out.println(country);
//show();// 普通的方法 不能直接调用 只能使用对象调用 静态方法可以直接调用
int a = 1000 ;
System.out.println(a);
// static int b = 200; 不能定义静态变量
}
}
测试类:
public class TestPerson {
public static void main(String[] args) {
// 创建对象
Person p1 = new Person();
p1.work();// 坚决不使用
Person.work();
}
}