【问题标题】:How to get information from an object? [duplicate]如何从对象中获取信息? [复制]
【发布时间】:2018-06-09 12:33:24
【问题描述】:

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

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

主要是

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 个对象。 id 为 0 的 John,id 为 1 的 Jane,id 为 2 的 Jim 和 id 为 3 的 Lucas。现在我想知道如何从 obj3 或其他对象获取信息。例如,我不知道对象的名称和 ID。我该怎么做?

【问题讨论】:

  • 您无法如此轻松地访问private 成员。提供 getters 或将 private 更改为其他访问说明符。你能修改personal_id 类吗?

标签: java


【解决方案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); 一样使用它,但这通常是不被接受的——它是被认为是一种不好的做法,因为它不能促进适当的对象封装。

旁注

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

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

你的构造函数也会增加id in:

id++;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多