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,加入到构造方法中去计算类产生的实例对象。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值