static定义属性

static关键字在Java程序开发过程中主要进行属性和方法的定义。

 

static 定义属性:

  类中的最主要的组成就是属性和方法,那么在说static之前,先看看一下问题:

范例:定义一个描述球的信息类:

 class Ball{
private String classify;
private double price;
private String brand;
public Ball(String classify,double price,String brand){
this.classify = classify;
this.price = price;
this.brand = brand;
}
public void getInfo(){
System.out.println("球的类型:"+this.classify+"、价格:"+this.price+"、品牌:"+this.brand);
}
}
public class Demo1{
public static void main(String[] args) {
Ball basketball = new Ball("篮球",100,"李宁");
Ball football = new Ball("足球",101,"李宁");
Ball pingpang = new Ball("乒乓球",99,"李宁");
basketball.getInfo();
football.getInfo();
pingpang.getInfo();
}
}

运行结果:

球的类型:篮球、价格:100.0、品牌:李宁
球的类型:足球、价格:101.0、品牌:李宁
球的类型:乒乓球、价格:99.0、品牌:李宁


当前的程序在Ball类里面定义有三个属性,这样就意味着每一个对象都拥有三个属性的内容,所以此时内存关系如下:

static定义属性_第1张图片

 

 

 

 


假设若有一天李宁品牌要被更换,且都要换为“姚明”球;
在这个场景下,若已经产生50W个球类,最终就需要修改50W次的brand属性。

package Staticmethod;
class Ball{
private String classify;
private double price;
public String brand;
public Ball(String classify,double price,String brand){
this.classify = classify;
this.price = price;
this.brand = brand;
}
public String getInfo(){
return "球的类型:"+this.classify+"、价格:"+this.price+"、品牌:"+this.brand;
}
}
public class Demo1{
public static void main(String[] args) {
Ball basketball = new Ball("篮球",100,"李宁");
Ball football = new Ball("足球",101,"李宁");
Ball pingpang = new Ball("乒乓球",99,"李宁");
basketball.brand = "姚明"; //修改品牌
System.out.println(basketball.getInfo());
System.out.println(football.getInfo());
System.out.println(pingpang.getInfo());
}
}

运行结果:
球的类型:篮球、价格:100.0、品牌:姚明
球的类型:足球、价格:101.0、品牌:李宁
球的类型:乒乓球、价格:99.0、品牌:李宁

static定义属性_第2张图片

 

 

现在所有所定义的属性都是普通的属性,那么这些属性在进行内存空间分配的时候都会将各自的属性内容保存在各自的堆内存的空间之中,然而对品牌这一概念,很明显应该是一个公共的属性,所以此时最好使用static来定义,即static 可以来定义公共属性,所有对象都拥有并且修改此公共属性的能力。

范例:

 

  class Ball{
private String classify;
private double price;
static String brand;
public Ball(String classify,double price,String brand){
this.classify = classify;
this.price = price;
this.brand = brand;
}
public String getInfo(){
return "球的类型:"+this.classify+"、价格:"+this.price+"、品牌:"+this.brand;
}
}
public class Demo1{
public static void main(String[] args) {
Ball basketball = new Ball("篮球",100,"李宁");
Ball football = new Ball("足球",101,"李宁");
Ball pingpang = new Ball("乒乓球",99,"李宁");
basketball.brand = "姚明";
System.out.println(basketball.getInfo());
System.out.println(football.getInfo());
System.out.println(pingpang.getInfo());
}
}

  

运行结果:

球的类型:篮球、价格:100.0、品牌:姚明
球的类型:足球、价格:101.0、品牌:姚明
球的类型:乒乓球、价格:99.0、品牌:姚明

此时发现,Ball 类之中 brand 属性追加了一个 static 关键字之后,只是用一个实例化对象修改了 brand 属性内容后,所有对象的brand属性的相关内容全部


 

你可能感兴趣的:(static定义属性)