java中新建一个对象,每个对象都有的自己的属性。如果现在有些属性希望被所有的对象共享,则就必须将其声明为static属性。如果一个类中的方法想由类调用,则可声明为static方法。
下面来看一个类:
package com.ydemo.array.test; public class Person { private String name; private static String city="A"; public Person(String name) { this.name = name; } public Person() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public static String getCity() { return city; } public static void setCity(String city) { Person.city = city; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + "city='" + city + '\'' + '}'; } }修改类中的属性进行测试
@Test public void test(){ Person person1 = new Person("张三"); Person person2 = new Person("李四"); Person person3 = new Person("王五"); System.out.println(person1.toString()); System.out.println(person2.toString()); System.out.println(person3.toString()); Person.setCity("B"); System.out.println(person1.toString()); System.out.println(person2.toString()); System.out.println(person3.toString()); }结果如下
Person{name=’张三’city=’A’} Person{name=’李四’city=’A’} Person{name=’王五’city=’A’} Person{name=’张三’city=’B’} Person{name=’李四’city=’B’} Person{name=’王五’city=’B’}
Person类中setCity()方法为static方法。
直接可以通过 Person.setCity("B");进行调用。
代码:
package com.ydemo.array.test; public class CountDemo { private static int count =0; public CountDemo() { count++; System.out.println("新建了"+count+"个对象"); } }test:
@Test public void test(){ new CountDemo(); new CountDemo(); new CountDemo(); new CountDemo(); }结果:
新建了1个对象 新建了2个对象 新建了3个对象 新建了4个对象