【问题标题】:How to return a new object by a method without parameters JavaJava如何通过不带参数的方法返回一个新对象
【发布时间】:2016-02-09 06:20:31
【问题描述】:

我是一名 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;

非常感谢

【问题讨论】:

  • 贴出Cell类的代码
  • 我已经编辑了我的问题!
  • 你在哪里定义的 division() 方法?
  • division 必须是访问封闭类实例的成员。关键字/标识符不是 object 而是 this
  • division 是该类的成员。我忘记了“这个”。它成功了。非常感谢!

标签: java methods copy copy-constructor


【解决方案1】:

由于您没有将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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2023-04-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    相关资源
    最近更新 更多