简体   繁体   English

如何通过不带参数Java的方法返回新对象

[英]How to return a new object by a method without parameters Java

I'm a Java beginner and wanted to ask how I can return a new object with a method with no parameters given. 我是Java初学者,想问一下如何使用不带参数的方法返回一个新对象。

The instructions are the following: «a method division without parameters, allowing the cell to divide; 指令如下:«没有参数的方法划分,允许单元划分; the method division returns a new Cell; 方法部门返回一个新的单元格; the new cell is a copy of the former cell; 新单元格是先前单元格的副本; the copy will then follow a mutation of its color;» 然后副本将跟随其颜色的变化;»

My question is, how do I implement the copy constructor in the method, so if I call Cell.division() that it will take "Cell" as an Object and copy it? 我的问题是,如何在该方法中实现复制构造函数,因此如果我调用Cell.division()它将以“ Cell”作为对象并复制它?

If I write 如果我写

    public Cellule division(){
    Cell tmpCell = new Cell(object);
   //some mutations I need to code
    return tmpCell;

it says "object" cannot be resolved to a variable 它说“对象”不能解析为变量

Code of the Cell Class: 单元类别的代码:

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;

Thanks a lot 非常感谢

Since you are not passing obeject as parameter and you are not declaring it as local variable its throwing "object" cannot be resolved to a variable error. 由于您没有将obeject作为参数传递,并且没有将其声明为局部变量,因此无法将其obeject "object" cannot be resolved to a variable错误。

So in your case it needs to be declared globally. 因此,在您的情况下,需要全局声明。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM