如何从对象获取信息?

时间:2017-12-29 01:20:58

标签: java

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

@ContributesAndroidInjector(modules = SetupDataServiceModule.class)
SetupDataService bindSetupDataService();

@Module interface SetupDataServiceModule {
  @Binds Service bindService(SetupDataService service);
  @Binds IntentService bindIntentService(SetupDataService service);
}

主要是

public class personal_id{
privete int id=0;
private String name;
public personal_id(String name){
name=this.name;
id++;
}
}

我想我已经创建了4个对象。 John为id 0,Jane为id 1,Jim为id 2,Lucas为id 3.现在我想知道如何从obj3或其他对象获取信息。例如,我不知道对象的名称和id。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

你有几个选择,但通常最好的方法是创建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());
    }
}

输出:

John's id: 1
John's name: John

一般来说,您还可以将属性的可见性从private更改为public(例如private int id = 0;更改为public int id = 0;)并将其用作System.out.println("John's id: "+ john.id);,但这通常是不赞成的 - 它被认为是一种不好的做法,因为它不会促进适当的对象封装。

图片的标题说明

从评论中可以看出,您的代码还存在其他一些问题。

首先,类的名称违反Java naming conventions and guidelines,其中类的名称应为camelCase。换句话说,您应该PersonalId而不是personal_id。此外,您应该使用Creator而不是creator(注意第一个字母,它应该是大写的。)

此外,您的构造函数会在{/ p>中增加id

id++;

但这没有多大意义,因为id声明的起始值为0private int id=0;),id的值始终为1施工结束后。