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,加入到构造方法中去计算类产生的实例对象。
烧不死的鸟就是凤凰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)