Creating an identifying variable and Cloning while modifying Variables

蓝咒 提交于 2019-12-11 04:36:42

问题


I have a class that creates Cars with a number of variables (year, brand, color, ... , sold (boolean), description (String), unique identifier (int) ).

In part of my project, I need to create a method to clone a Car, maintaining all variables except sold (reverts to SOLD_DEFAULT) description (reverts to DESC_DEFAULT) and unique identifier (generates a new identifier).

For now, my cloning code looks like this:

public Automobile cloner () {
        Automobile Clone = new Automobile(brand,year,color,a,k,p,DESC_DEFAULT,SOLD_DEFAULT);
        return Clone;     
    }

I have seen myself forced to include all the variables in () of the new instance or else I get an error: it sees no arguments.

My question is towards the identifying variable. It needs to be declared as an int that is private to my Automobile class, basically acting as a counter with the first car automatically having the identifying number = 1, second car = 2, etc... and if a car is cloned, identifying number goes up by one for the new instance. How would I go about doing that in my cloning method, and would I have to modify the way I clone the car ?

Also, let's say I have cars stocked in a table at slots 0 and 1, with slots 2, 3 empty, as in:

Automobile [] stock = new Automobile [4];

If I input these instructions:

Automobile aRandomCar;
  aRandomCar = stock[ 0 ];
  stock[ 3 ] = aRandomCar;
  stock[ 2 ] = stock[ 1 ].cloner();

and then I modify the year for stock[3] and the color for aRandomCar. Since it is an equality and not a new instance (like stock[2]), would this mean that my changing the year for stock[3] I also change it for aRandomCar and vice versa?

Thanks a lot !!!!

P.S.: Please refer to Getters, Setters and Constructors in Java - Making a car and stocking it for further parts of code from my Class.


回答1:


Try to realize clone method from Object class and implement Cloneable interface. Use super.clone() to clone simple fields and manually clone composite fields.

Composite fields like your's classes not cloning itself. Only reference clones for you composite fields



来源:https://stackoverflow.com/questions/40999497/creating-an-identifying-variable-and-cloning-while-modifying-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!