Java 如何从对象获取信息?

Java 如何从对象获取信息?,java,Java,我有两节课 第二个看起来像 这: 主要是 public class creator{ public static void main(String[]arg){ personal_id obj1=new personal_id("John"); personal_id obj2=new personal_id("Jane"); personal_id obj3=new personal_id("Jim"); personal_id obj4=new personal_id("Lucas"); }

我有两节课 第二个看起来像 这:

主要是

public class creator{
public static void main(String[]arg){
personal_id obj1=new personal_id("John");
personal_id obj2=new personal_id("Jane");
personal_id obj3=new personal_id("Jim");
personal_id obj4=new personal_id("Lucas");
}
}

我想我已经创建了4个对象。身份证号为0的约翰、身份证号为1的简、身份证号为2的吉姆和身份证号为3的卢卡斯。现在我想知道如何从obj3或其他对象获取信息。例如,我不知道对象的名称和id。我该怎么做呢?

您有两个选择,但通常最好的方法是创建getter:

public class PersonalId { // ------------------- renamed: it was "personal_id"
    private int id = 0;   // ------------------- fixed: was "privete" instead of "private"
    private String name;
    public PersonalId(String name) { // ------------------- renamed: it was "personal_id"
        this.name = name; // ----------------- fixed: was "name = this.name"
        id++; // this line makes little sense, it's the same as declaring id = 1;
    }

    public int getId() {      // ------------------- added
        return this.id;       // ------------------- added
    }                         // ------------------- added
    public String getName() { // ------------------- added
        return this.name;     // ------------------- added
    }                         // ------------------- added
}
然后像这样使用它:

public class Creator { //  -------------- renamed: was "creator"
    public static void main(String[] arg) {
        PersonalId john = new PersonalId("John");
        System.out.println("John's id: "+ john.getId());
        System.out.println("John's name: "+ john.getName());
    }
}
输出:

约翰的身份证:1
约翰的名字:约翰
一般来说,您还可以将属性的可见性从
private
更改为
public
(例如
private int-id=0;
更改为
public int-id=0;
),并像
System.out.println(“John的id:+John.id”)那样使用它,但这通常是不受欢迎的——这被认为是一种不好的做法,因为它不能促进适当的对象封装

旁注 从注释中可以看出,您的代码还存在一些其他问题

首先,类的名称冲突,其中类的名称应该是camelCase。换句话说,您应该拥有
个人id
,而不是
个人id
。另外,您应该使用
Creator
而不是
Creator
(注意第一个字母,它应该是大写)

此外,您的构造器在以下位置递增
id

id++;

但这没有什么意义,因为
id
是以
0
的起始值(
private int id=0;
)声明的,
id
的值在构造之后总是
1

您无法如此轻松地访问
private
成员。提供getter或将
private
更改为其他访问说明符。您是否可以修改
个人id
类?
id++;