Static 声明属性
Static 方法不能调用非static 属性或者代码
应用 static 可以声明共有的属性 方便一改全部改
案例1:定义一个静态属性 然后用静态方法进行改变
class Demo
{
private int age=25;
private String name="周海峰";
private static String city="A城市";//当不适用static的时候 没产生一个对象 那么它的city 属性确实一样
public Demo(int age,String name) {
this.setAge(age);
this.setName(name);
} //因为我并没有使用构造方法对每一个对象进行赋值
public void setAge(int age){ //这样做的问题是我没法批量修改 city 属性
this.age=age; //加上static 关键字以后我可以批量修改city 属性
}
public void setName(String name ){
this.name=name;
}
public static void setCity(String c){
city=c; //此处不可以用this.city 因为 this 是具体的对象
}
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
public static String getCity(){
return city;//此处不可以用this.city 因为 this 是具体的对象
}
}
public class NewDemo
{
public static void main(String args[]){
Demo de1=new Demo(23,"周海峰");
Demo de2=new Demo(24,"安日成");
System.out.println(de1.getAge()+","+de1.getName()+","+de1.getCity());
System.out.println(de2.getAge()+","+de2.getName()+","+de2.getCity());
System.out.println("----------------设置之后------------------------");
Demo.setCity("B城市");
System.out.println(de1.getAge()+","+de1.getName()+","+de1.getCity());
System.out.println(de2.getAge()+","+de2.getName()+","+de2.getCity());
}
}
运行的结果为:
案例2 在类的构造函数中定义一个静态属性,用于统计产生的对象的个数
class Demo
{
private int age=25;
private String name="周海峰";
static int counter=0;
private static String city="A城市";//当不适用static的时候 没产生一个对象 那么它的city 属性确实一样
public Demo(int age,String name) {
this.setAge(age);
this.setName(name);
counter++;
System.out.printf("\n已经产生了"+counter+"个对象");
} //因为我并没有使用构造方法对每一个对象进行赋值
public void setAge(int age){ //这样做的问题是我没法批量修改 city 属性
this.age=age; //加上static 关键字以后我可以批量修改city 属性
}
public void setName(String name ){
this.name=name;
}
public static void setCity(String c){
city=c; //此处不可以用this.city 因为 this 是具体的对象
}
public int getAge(){
return this.age;
}
public String getName(){
return this.name;
}
public static String getCity(){
return city;//此处不可以用this.city 因为 this 是具体的对象
}
}
public class NewDemo
{
public static void main(String args[]){
Demo de1=new Demo(23,"周海峰");
System.out.println(de1.getAge()+","+de1.getName()+","+de1.getCity());
Demo de2=new Demo(24,"安日成");
System.out.println(de2.getAge()+","+de2.getName()+","+de2.getCity());
System.out.println("----------------设置之后------------------------");
Demo.setCity("B城市");
System.out.println(de1.getAge()+","+de1.getName()+","+de1.getCity());
System.out.println(de2.getAge()+","+de2.getName()+","+de2.getCity());
}
}
运行的结果为: