static关键字的介绍
static关键字——实现共享
(一)static类属性
- 描述共享属性,只需在属性前添加static关键字即可 ;
- 访问static属性(类属性)应使用类名称.属性名 ;
- static属性又称为类属性,保存在全局数据区的内存之中,所有对象都可以进行该数据区的访问;
- 只需要一份数据,就可以在整个类中实现共享;
- 所有的非static属性(实例变量)必须在对象实例化后使用,而static属性(类属性)不受对象实例化控制;
此时,我们修改static属性值,所有对象都同步此属性值。
static类属性举例如下:
class Person2{
//此处为了强调static关键字的作用,设为公共属性
public static String country = "中国";
public String name;
public int age;
//构造方法
public Person2(String name,int age){
this.name = name;
this.age = age;
}
//方法
public void intriduce(){
System.out.println("姓名:"+name+",年龄:"+age+",国家:"+country);
}
}
public class Test3{
public static void main(String[] args){
Person2 sg1 = new Person2("kelly",21);
Person2 sg2 = new Person2("张三",20);
sg1.intriduce();
sg2.intriduce();
}
}
运行结果如下:
修改static属性值,所有对象都同步此属性值
class Person2{
//此处为了强调static关键字的作用,设为公共属性
public static String country = "中国";
public String name;
public int age;
//构造方法
public Person2(String name,int age){
this.name = name;
this.age = age;
}
//方法
public void intriduce(){
//此处修改static属性值,所有对象的属性值同步修改
Person2.country = "韩国";
System.out.println("姓名:"+name+",年龄:"+age+",国家:"+country);
}
}
结果如下:
(二)static类方法
-
不用创建对象就可以访问static类方法;
-
访问形式:
1,类名.方法名
2,通过实例化对象访问 -
所有的static方法不允许调用非static定义的属性或方法;
-
所有的非static方法允许访问static方法或属性 。
举例如下:
class Person2{
//此处为了强调static关键字的作用,设为公共属性
public static String country = "中国";
public String name;
public int age;
//构造方法
public Person2(String name,int age){
this.name = name;
this.age = age;
}
//方法
public static void print(){
System.out.println("hehehe");
}
public void intriduce(){
Person2.country = "韩国";
System.out.println("姓名:"+name+",年龄:"+age+",国家:"+country);
}
}
public class Test3{
public static void main(String[] args){
//1,使用类名.方法名调用static方法
Person2.print();
//2,实例化对象调用static方法
Person2 sg1 = new Person2("kelly",21);
sg1.print();
}
}
运行结果如下: