JAVA-static关键字

来源:互联网 发布:24小时私人网络上借钱 编辑:程序博客网 时间:2024/06/01 13:11

一。使用static声明属性

1.static声明全局属性

class Person{String name;int age;static String country="China";//设置静态城市属性public Person(String name,int age){this.name = name;this.age = age;}public void info(){System.out.println("姓名"+this.name+"年龄"+this.age+"城市"+country);}};public class csdnTest21{public static void main(String arg[]){Person p1 = new Person("张三",30);Persom p2 =new Person("李四",40);Person P3 = new Person("王五",50);System.out.println("before");p1.info();p2.info();p3.info();p1.country = "B城";System.out.println("before");//修改一个对象的country属性,则其他country属性内容全部改变p1.info();p2.info();p3.info();}};
1.栈内存:可以保存对象的名称(保存访问堆内存的地址

2.推内存:保存对象的具体属性

3.全局数据区:保存static类型的属性

4全局代码区 保存所有方法的定义

一般在调用static属性时候最好使用类名称例如 Person.country =B



二。声明static方法

如果一个方法使用static关键字声明,则此方法可以直接使用类名称进行调用

public static void setCountry(String c){   //此方法直接由类名称调用country = c;
三。其他运用

1.统计一个类产生多少个实例化对象

方法:在构造方法添加static

class Demo{private static int count = 0; //对象共享此属性public Demo(){count++;System.out.println("产生了"+count+"个对象");}};public class csdnTest23{public static void main(String arg[]){new Demo();//增加新对象<span style="white-space:pre"></span>//输出产生一个对象new Demo();//增加新对象new Demo();//增加新对象}};
2.使用static对象进行自动命名操作

class Demo{// 定义Person类private String name ;// 保存名字private static int count = 0 ;// 所有对象共享此属性public Demo(){count++ ;// 有对象产生就自增this.name = "DEMO-" + count ;// 自动进行编名操作} public Demo(String name){this.name = name;// 可以通过构造赋值}public String getName(){// 取得姓名return this.name ;}};public class csdnTest23{public static void main(String args[]){System.out.println(new Demo().getName()) ;System.out.println(new Demo("LXH").getName()) ;System.out.println(new Demo().getName()) ;System.out.println(new Demo("MLDN").getName()) ;System.out.println(new Demo().getName()) ;}};



0 0
原创粉丝点击