Click here to Skip to main content
15,890,946 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I am new to OOP. I had to create "structs" from C# but in Java it doesn't exist so i created class. This class is called person. And there are some info about person(child) in class string, and float types. In my program sometimes i need to generate new person. I guess that's called creating new instance, sorry if i am wrong. Because I need to use infos for spesific person later. So i thought i could name them person01,person02 or by their names. But i can't do it. Is there a way to do it? Or is there any solution way for this? Maybe there is easy different way to do it that i do not know.


BTW
Java
public class child {
	public static String name;
	public static float foodConsumed;
	public static float sleepConsumed;
	public static float gameConsumed;
	public static float hygieneConsumed;
	
	public static void add(){
		Random rnd = new Random();
		child.name="child"+num;
		child.foodConsumed= (float) ((rnd.nextInt(150)+50)*0.01);
		child.gameConsumed= (float) ((rnd.nextInt(150)+50)*0.01);
		child.sleepConsumed= (float) ((rnd.nextInt(75)+25)*0.01);
		child.hygieneConsumed= (float) ((rnd.nextInt(50)+20)*0.01);
		Main.num++;
		Main.childQnt++;
	}
}


This childs i have to generate later..

What I have tried:

I tried to use variable which changes like child01,child02:
child variable = new child();

But this didn't quite work.
Posted

1 solution

No and it will never work because you have made all the properties static, so they apply to every instance of child. Remove the static keyword from all those properties, and then you can create any number of objects like:
Java
child Robert = new child();
Robert.name = "Robert";
// ...
child Mary = new child();
Mary.name = "Mary";
// etc

See Lesson: Classes and Objects - Learning the Java Language)[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900