一、static关键字定义属性
• 使用static定义的属性表示类属性,类属性可以由类名称直接进行调用;
• static属性虽然定义在了类之中,但是其可以在没有实例化对象的时候进行调用(普通属性保存在堆内存里,而static属性保存在全局数据区之中);
在java中static关键字可以定义属性和方法。
class Person {
private String name;
private int age;
String country = "北京";
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getInfo() {
return "姓名:" + this.name + ",年龄:" + this.age + ",城市:" + this.country;
}
}
public class TestDemo {
public static void main(String args[]) {
Person per1 = new Person("张三", 20);
Person per2 = new Person("李四", 21);
System.out.println(per1.getInfo());
System.out.println(per2.getInfo());
}
}
以上的程序内存分配如下:
很明显 country属性是相同的:对于有公有属性的成员变量使用static关键字完成
class Person {
private String name ;
private int age ;
static String country = "北京" ;
public Person(String name,int age) {
this.name = name ;
this.age = age ;
}
public String getInfo() {
return "姓名:" + this.name + ",年龄:" + this.age + ",城市:" + this.country ;
}
}
public class TestDemo {
public static void main(String args[]) {
Person per1 = new Person("张三",20) ;
Person per2 = new Person("李四",21) ;
per1.country = "青岛" ;
System.out.println(per1.getInfo()) ;
System.out.println(per2.getInfo()) ;
}
}
以下是程序在内存中的分配情况
当new (类名)时才会在堆内存中开辟一个空间,其中的方法才可以被调用。
1.只想为某特定域分配单一存储空间,而不去考虑究竟要创建多少个对象,甚至根本不需要创建任何对象。
2.希望某个方法不与包含他的类的任何对象关联在一起。也就是说,即使没有创建对象,也能够调用方法。
二、使用static关键字定义方法
使用static定义的方法同样可以在对象初始化之前被调用
class Person {
private String name ;
private int age ;
private static String country = "北京" ;
public Person(String name,int age) {
this.name = name ;
this.age = age ;
}
public static void setCountry(String c) {
country = c ;
}
public static String getCountry() {
return country ;
}
public String getInfo() {
return "姓名:" + this.name + ",年龄:" + this.age + ",城市:" + this.country ;
}
}
public class TestDemo {
public static void main(String args[]) {
Person.setCountry("青岛") ; // 类.static方法()
System.out.println(Person.getCountry()) ;
Person per1 = new Person("张三",20) ;
System.out.println(per1.getInfo()) ;
}
}
三、在实际的使用过程中使用static关键字
1.统计生成对象的个数
一个类在使用过程中会被调用多次。一个类中的构造器(用户没有定义自己的构造器,jvm会默认生成一个无参构造器)在初始化时构造器一定会被调用,因此可以在构造器中使用static定义变量
class Person {
private static int count = 0 ;
public Person() {
System.out.println("对象个数:" + ++ count) ;
}
}
public class TestDemo {
public static void main(String args[]) {
new Person() ;new Person() ;new Person() ;
}
}
初学还望指正