Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java creating new object

I have an abstract class Specie, and then class Animals which extends species, and then my classes for animals (e.g. Sheep). In Animals I have a method which checks if two objects are on the same position on the map, and if the are the same type (e.g. Sheep and Sheep).

If yes it creates another Sheep. And I have problem with that I tried something like that

Specie new_specie = this;

And I have a copy consturctor in my Sheep class

     public Sheep(Sheep new_sheep){

     this(new_sheep.get_x(),new_sheep.get_y(), new_sheep.get_img());
}

And then save it to the array which contains all the objects

species[speciesAmount] = new_specie;

But it just saves the same object in two elements of an array

species[0]
species[2]

same object. Any ideas?

But there is another problem, I'll have more types of animals(eq. Wolf) and I can't do

new Specie(this)

because it's an abstract class.

How to make it to call the proper constructor?

edit. I solved it, I used clone() method.

like image 871
Cardano Avatar asked Aug 26 '26 08:08

Cardano


2 Answers

Specie new_specie = this; will just create a new reference called new_specie and let it refer to the same object as this. Hence species[speciesAmount] = new_specie; will assign the same reference to the array entry (which is itself a reference).

Your code doesn't call the copy constructor at all. Unlike C++ in Java calling a copy constructor has to look like this:

Specie new_specie = new Sheep(this);

Btw, you might want to have a look into the Clonable interface which is meant to provide for object copying.

Update: Regarding your second question the solution depends on what you want to achieve. If you just want a copy of the concrete species that is on a field whenever there are two of them, you could just compare the classes of both species (using the getClass() method) or check equality using equals() (depends on how you define that, it's often more than equal classes).

Then you basically just call Species new_species = species_on_field.clone() and get a clone of what was on that field before.

Another option might be to use the factory pattern or a prototype based on the class of the current species on that field. I'll leave those for you to look up on the net though.

like image 90
Thomas Avatar answered Aug 27 '26 21:08

Thomas


In Java, you can't call a copy constructur with an assignment. You have to call it!

species[0] = new Sheep(this);
like image 37
Peter Clause Avatar answered Aug 27 '26 23:08

Peter Clause



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!