Reputation: 37
I want to show the message "Object number 1", "Object number 2", etc... each time that an object is created.
I'm a beginner in programmation so I just want to know if this is correct (despite the fact that it works) :
public class Test {
public static void main (String [] args) {
Point pt1 = new Point();
Point pt2 = new Point();
}
}
class Point {
private static int nb = 0;
{
++nb;
System.out.println("Object number : " + nb);
}
}
Upvotes: 1
Views: 100
Reputation: 32145
Yes it's correct the way you are using the static
variable.
Just move the code that increments and prints it to the class constructor instead of using an initialization block.
Because in OOP a class constructor is what get called when a new instance of the class is created, so that's the most appropriate place to put similar code that needs to be executed when we create a new instance.
public class Test {
public static void main(String[] args) {
Point pt1 = new Point();
Point pt2 = new Point();
}
}
class Point {
private static int nb = 0;
public Point() {
System.out.println("Object number : " + (++nb));
}
}
If you take a look at Providing Constructors for Your Classes you can see that:
A class contains constructors that are invoked to create objects from the class blueprint.
Upvotes: 1
Reputation: 4506
It is not threadsafe:
public class Test {
public static void main(String[] args) {
IntStream.range(1, 100).parallel().forEach(i -> new Point());
}
}
class Point {
private static int nb = 0;
public Point() {
++nb;
System.out.println("Object number : " + nb);
}
}
It can produce same "id" several times
Upvotes: 1
Reputation: 553
Try to put these 2 lines in a constructor.
++nb;
System.out.println("Object number : " + nb);
If you need to an executable code in your java program It must an should be in a constructor or in a method.
public class Test {
public static void main (String [] args) {
Point pt1 = new Point();
Point pt2 = new Point();
}
}
class Point {
private static int nb = 0;
public Point()
{
++nb;
System.out.println("Object number : " + nb);
}
}
Upvotes: 1
Reputation: 3381
This will actually work. When creating a block inside the class, this code will be executed before the constructor is invoced.
public class Point{
{
//invoked before constructor
}
public Point() {
//Constructor code
}
}
When you have no constructor or only one constructor, it is more readable to put this code inside the constructor:
public Point() {
System.out.println("Object number : " + ++nb);
}
Other people who read your code will thank you!
Upvotes: 1
Reputation: 130
You need to put your code into a constructor. Like this:
class Point
{
private static int nb = 0;
public Point()
{
++nb;
System.out.println("Object number : " + nb);
}
}
Upvotes: 1