static关键字
1) 简介
Java中提供了一个关键字:static 可以被多个对象“共享”“共用”, 在需要共享的对象前加入这个属性。
//定义一个类:人类
class Person{//Preson.class
private String name ; //姓名
private int age ; //年龄
static String country ;//国籍
//有参构造方法
//带两个参数的构造方法
public Person(String name,int age){
this.name = name ;
this.age = age ;
}
public Person(String name,int age ,String country){
this.name = name ;
this.age = age ;
this.country = country ;
}
public void show(){
System.out.println("这个人姓名是-"+name+",年龄是-"+age+",所在的国籍是-"+country) ;
}
}
//测试类
class PersonTest{
public static void main(String[] args){
//古代四大美女
Person p1 = new Person("西施",18,"中国") ;
p1.show() ;
System.out.println("------------------------") ;
//Person p2 = new Person("貂蝉",25,"中国") ;
Person p2 = new Person("貂蝉",25) ;
p2.show() ;
System.out.println("------------------------") ;
//Person p3 = new Person("杨玉环",28,"中国") ;
Person p3 = new Person("杨玉环",28) ;
p3.show() ;
System.out.println("------------------------") ;
//Person p4 = new Person("王昭君",23,"中国") ;
Person p4 = new Person("王昭君",23) ;
p4.show() ;
System.out.println("------------------------") ;
p1.country = "美国" ;
p1.show() ;
p2.show();
p3.show();
p4.show() ;
}
}
2.关键字的特点:
① static 随着类的加载而加载(生命周期---->xxx.class :static相关的都先进内存!)
②优先于对象存在
类的加载:类名.class(优先的)
对象的创建: 类名 对象名=new 类名;
③不能和this公用
④被静态修饰的变量或方法(静态变量/静态方法);有共享,公用的意思;
⑤被静态修饰的变量和方法,推荐使用类名+变量名/方法名:
类名.静态变量名;
类名.静态方法名();
不推荐使用:
对象名.静态变量名;
对象名.静态方法名;
例:
class Demo{
//成员变量
int num = 10 ;
//静态变量
static int num2 = 20 ;
//成员方法
public void function(){
System.out.println("function demo...") ;
}
//静态方法
public static void method(){
System.out.println("method demo...") ;
}
}
//测试类
class StaticDemo{
public static void main(String[] args){
//需求:要访问Demo类中的num和num2变量?
Demo d = new Demo() ;
System.out.println(d.num) ;
//System.out.println(d.num2) ; //静态变量不这样访问:不推荐!
System.out.println(Demo.num2) ; //静态的成员的访问方式
System.out.println("---------------------") ;
d.function() ;
//d.method() ;//不推荐
//推荐方式
Demo.method() ;
}
}
3.使用的注意事项:
①非静态的成员方法:
可以访问静态和非静态的成员变量和成员方法。
②静态的方法
静态只能访问静态!(静态的变量和方法都跟类相关!)