static关键字的使用
package com.liaojianya.chapter2;
/**
* static关键字的使用
* @author LIAO JIANYA
* 2016年7月28日
*/
public class StaticDemo
{
public static void main(String[] args)
{
People p1 = new People("zhangsan", 20);
People p2 = new People("lisi", 21);
People p3 = new People("wangwu", 22);
System.out.println("Before modifying the information: " + p1.talk());
System.out.println("Before modifying the information: " + p2.talk());
System.out.println("Before modifying the information: " + p3.talk());
System.out.println("*************After modifying the information************");
p1.city = "The USA";
System.out.println("After modifying the information: " + p1.talk());
System.out.println("After modifying the information: " + p2.talk());
System.out.println("After modifying the information: " + p3.talk());
People.print();
}
}
class People
{
String name;
static String city = "nanjing";
int age;
static int i = 0;
public People(String name, int age)
{
i++;
this.name = name;
this.age = age;
}
public String talk()
{
return "My name is " + this.name + ", I'm " + this.age + "years old, I'm from " + city;
}
public static void print()
{
System.out.println("产生了:" + i + " 个实例对象");
}
}
运行结果:
Before modifying the information: My name is zhangsan, I'm 20years old, I'm from nanjing
Before modifying the information: My name is lisi, I'm 21years old, I'm from nanjing
Before modifying the information: My name is wangwu, I'm 22years old, I'm from nanjing
*************After modifying the information************
After modifying the information: My name is zhangsan, I'm 20years old, I'm from The USA
After modifying the information: My name is lisi, I'm 21years old, I'm from The USA
After modifying the information: My name is wangwu, I'm 22years old, I'm from The USA
产生了:3 个实例对象
分析:
1)static声明的属性city是所有对象共享的,所以,p1调用的属性city改变其值,全部对象的city都发生了同样的变化。
2)使用static修饰的属性i,加入到构造方法中去计算类产生的实例对象。
烧不死的鸟就是凤凰