1. 程式人生 > >java中如何使用空參構造方法自動生成不同名字的對象,使用非靜態的屬性和靜態屬性有什麽區別,原因是什麽?如何理解static關鍵字

java中如何使用空參構造方法自動生成不同名字的對象,使用非靜態的屬性和靜態屬性有什麽區別,原因是什麽?如何理解static關鍵字

區別 關鍵字 內部 方法 屬性 count per setname person

空參構造自動生成對象時,使用非靜態的屬性

代碼:

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 ;
    }
    
}

結果:

技術分享

java中如何使用空參構造方法自動生成不同名字的對象,使用非靜態的屬性和靜態屬性有什麽區別,原因是什麽?如何理解static關鍵字