Java OOP Counter the object | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Java OOP Counter the object

How can I count the number of object by using Static ?

2nd Dec 2019, 1:07 AM
에이미
에이미 - avatar
3 Answers
+ 2
public class MyObject{ static int counter = 0; public MyObject(){ counter++; } } Inside main: MyObject.counter -> print it or assign it to a variable
2nd Dec 2019, 9:42 AM
Denise Roßberg
Denise Roßberg - avatar
2nd Dec 2019, 1:31 AM
BroFar
BroFar - avatar
+ 1
Create a static variable and increment it inside the constructor of the class.
2nd Dec 2019, 3:07 AM
Avinesh
Avinesh - avatar