java中如何使用空参构造方法自动生成不同名字的对象,使用非静态的属性和静态属性有什么区别,原因是什么?如何理解static关键字

JAVA学习网 2017-10-24 12:56:03

空参构造自动生成对象时,使用非静态的属性

代码:

package com.swift;
//使用无参构造方法自动生成对象,序号不断自增
public class Person {
    private int count; //如果在定义类时,使用的是非静态的属性,则得到的结果都是相同的,都为1。因为这个count生命周期短,只在对象内部
    public int id;
    public String name;
    public int age;
    public String city;
    public Person() {
        super();
        count++;
        this.id=count;
        this.name="NoName-"+count;
        this.age=20;
        this.city="蜀国"+count;
        
    }
    public Person(int id ,String name,int age,String city) {
        this.id=id;
        this.name=name;
        this.age=age;
        this.city=city;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getInfo() {
        return "The Person is id=" + id + ", name=" + name + ", age=" + age + ", city=" + city ;
    }
    
}

结果:

空参构造自动生成对象时,使用静态的属性

代码:

package com.swift;
//使用无参构造方法自动生成对象,序号不断自增
public class Person {
    private static int count; //如果在定义类时,使用的是静态的属性,则得到的结果是不同的。count生命周期长,与类相同
    public int id;
    public String name;
    public int age;
    public String city;
    public Person() {
        super();
        count++;
        this.id=count;
        this.name="NoName"+count;
        this.age=20;
        this.city="蜀国";
        
    }
    public Person(int id ,String name,int age,String city) {
        this.id=id;
        this.name=name;
        this.age=age;
        this.city=city;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getInfo() {
        return "The Person is id=" + id + ", name=" + name + ", age=" + age + ", city=" + city ;
    }
    
}

结果:

 

阅读(780) 评论(0)