关于static的用法
首先要了解:
-
static是一个关键字,可以用来定义属性和方法。
-
在一个类中,一个属性一旦被定义,其内容将会交给一个堆内存来保存
下面使用一个代码示例来解析static的作用
class Employees{//员工类
private long id;//id编号
private String name;//姓名
private String company;//公司名
public Employees() {//无参构造
}
public Employees(long id,String name,String company) {//有参构造
this.id=id;
this.name=name;
this.company=company;
}
public void getId(long id){
this.id=id;
}
public void getName(String name) {
this.name=name;
}
public void getCompany(String company)
{
this.company=company;
}
public String getInfo(){//将员工类的信息返回方法
return "编号:"+this.id+"|姓名:"+this.name+"|公司:"+this.company;
}
}
public class Static {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Employees one = new Employees(000001,"小白","威控");
Employees tow = new Employees(000002,"小黑","威控");
Employees three= new Employees(000003,"大白","威控");
System.out.println(one.getInfo());
System.out.println(tow.getInfo());
System.out.println(three.getInfo());
}
}
程序的运行结果如下
上述代码属于一个普通的java简单类,但是如果公司名发生了变化,但此时已经产生了将近上千个员工类对象,面对大量高重复的属性修改时应如何修改
错误示例
在Employees类不变的情况下
public class Static {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Employees one = new Employees(000001,"小白","威控");
Employees tow = new Employees(000002,"小黑","威控");
Employees three= new Employees(000003,"大白","威控");
one.getCompany("腾旭");//在此处修改company的属性
System.out.println(one.getInfo());
System.out.println(tow.getInfo());
System.out.println(three.getInfo());
}
输出结果如下:
因为此时各个对象之间的内存关系为:
如果要修改对象只能逐个修改
这时候static的作用就派上了用场
static可以将属性放置全局
如果将company设置为static属性则该属性的内存关系则成为下图所示:
添加static属性后的代码如下
class Employees{
private long id;
private String name;
private static String company;//--------------------------------将company设置为全局静态变量
public Employees() {
// TODO 自动生成的构造函数存根
}
public Employees(long id,String name,String company) {
this.id=id;
this.name=name;
this.company=company;
}
public void getId(long id){
this.id=id;
}
public void getName(String name) {
this.name=name;
}
public static void getCompany(String company_get)//--------------封装获取值的方法设置为static方法
{
company=company_get;//静态变量可以由类直接调用,无需this声明
}
public String getInfo(){
return "编号:"+this.id+"|姓名:"+this.name+"|公司:"+this.company+;
}
}
public class Static {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Employees one = new Employees(000001,"小白","威控");
Employees tow = new Employees(000002,"小黑","威控");
Employees three= new Employees(000003,"大白","威控");
one.getCompany("腾旭");//-----------------------------------一个对象进行commany修改
System.out.println(one.getInfo());
System.out.println(tow.getInfo());
System.out.println(three.getInfo());
}
}
此时的代码运行结果为: