I want to create a java class with a data member say id
such that each object has its own id
but the object id is assigned during object creation and then it can not be modified later.
Asked
Active
Viewed 44 times
0

user3282758
- 1,379
- 11
- 29
-
5Make it final and initialize once in constructor. – Pshemo Aug 16 '16 at 08:01
-
Use final, which can be assigned in constructor. – Rishi Goel Aug 16 '16 at 08:01
-
Is the fact that each object must have a *different* `id` part of the problem? – Ray O'Kalahjan Aug 16 '16 at 08:03
-
it should be a final attribute – Kallel Omar Aug 16 '16 at 08:03
1 Answers
5
public class Test {
private final int id;
public Test(int id) {
this.id = id;
}
}
A as final declared variable can only be initialized one time. At definition or at constructor.

Rene M.
- 2,660
- 15
- 24
-
I think without setter your id will not be changed as only way to supply it is *constructor* :) – akash Aug 16 '16 at 08:09
-
1