我是一名Java初学者,想要问我如何使用没有给出参数的方法返回一个新对象。
说明如下: «没有参数的方法划分,允许细胞分裂; 方法除法返回一个新的Cell;新细胞是前细胞的副本;然后,副本将跟随其颜色的变异;»
我的问题是,如何在方法中实现复制构造函数,所以如果我调用Cell.division()它会将“Cell”作为对象并复制它?
如果我写
public Cellule division(){
Cell tmpCell = new Cell(object);
//some mutations I need to code
return tmpCell;
它说“对象”无法解析为变量
细胞类代码:
private String nom;
private double taille;
private int energie;
private String couleur;
//default
public Cellule(){
nom = "Pyrobacculum";
taille = 10;
energie = 5;
couleur = "verte";
}
//copy constructor
public Cellule(Cellule autreCellule){
energie = autreCellule.energie;
taille = autreCellule.taille;
nom = autreCellule.nom;
couleur = autreCellule.couleur;
}
//parameters
public Cellule(String nom, double taille, int energie, String couleur){
this.taille = taille;
this.energie = energie;
this.nom = nom;
this.couleur = couleur;
}
//return Energy
public int getEnergie(){
return energie;
}
//return Height
public double getTaille(){
return taille;
}
//outprint
public void affiche(){
System.out.println(nom + ", taille = " + taille + " microns, énergie = "
+ energie + ", couleur = " + couleur );
}
//division method
public Cellule division(){
Cell tmpCell = new Cell(object);
//some mutations I need to code
return tmpCell;
非常感谢
答案 0 :(得分:0)
由于您没有将obeject
作为参数传递,并且您没有将其声明为局部变量,因此抛出"object" cannot be resolved to a variable
错误。
所以在你的情况下,它需要全局声明。
class Cell {
int i;
Cell c= new Cell(2);
Cell(Cell clone ) {
this.i = clone.i;
}
Cell(int i ) {
this.i = i;
}
public Cell division(){
Cell tmpCell = new Cell(c);
return tmpCell;
}
}