You have a couple of options, but the generally best approach here is to create getters:
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
}
And use it like:
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());
}
}
Output:
John's id: 1
John's name: John
Generally speaking, you could also change the properties’ visibility from private
to public
(e.g. private int id = 0;
to public int id = 0;
) and use it like System.out.println("John's id: "+ john.id);
, but that is generally frowned upon — it is considered a bad practice since it does not foster proper object encapsulation.
Sidenotes
As you can see from the comments, your code also had some other problems.
Firstly, the name of the classes violate Java naming conventions and guidelines, in which the name of classes should be camelCase. In other words, you should have PersonalId
instead of personal_id
. Also, you should use Creator
instead of creator
(notice the first letter, it should be uppercase).
Also your constructor increments id
in:
id++;
But that makes little sense, since id
is declared with a starting value of 0
(private int id=0;
), id
‘s value will always be 1
after the construction.
0
solved How to get information from an object? [duplicate]