关于类和方法的问题-在方法内部创建类的对象

时间:2019-04-16 01:41:51

标签: java

在方法内部创建对象时,我感到困惑。

例如在此编码中;我不确定为什么要放公共空隙的眼镜(Ventana w),为什么要放这个?在第二种方法中,很明显,因为我们要将此值设置为变量,但是在第一种方法中,我不知道我要做什么。

我希望有人能帮助我。

Class Ventana
{
    public void copiar(Ventana w) {
    }
    public void copiar(String p, int xx, int y) {
    }
}

谢谢!

2 个答案:

答案 0 :(得分:0)

就像Elliott上面评论的那样。 使用以Ventana作为参数的此方法,复制Ventana更为实用。

例如:

Class Ventana{

    private String style;
    private int height;
    private int wide;

    public void copiar(Ventana w) {
       this.style = w.getStyle();
       this.height = w.getHeight();
       this.wide = w.getWide();
    }

    public void copiar(String style, int height, int wide) {
       //...
    }
}

可能最好有足够的构造函数:

public Ventana (String style, int height, int wide){
       this.style = style;
       this.height = height;
       this.wide = wide;
}

然后将复制方法设置为:

public Ventana copiar(Ventana w) {
       return new Ventana(w.getStyle(), w.getHeight(), w.getWide());
    }

答案 1 :(得分:0)

在两行之间阅读,好像您没有提供完整的代码,也许您正在尝试这样做?

Class Ventana
{
   string p;
   int xx;
   int y;

   public static Ventana(Ventana w)
   {
      Ventana copy = new Ventana();
      copy.p = w.p;
      copy.xx = w.xx;
      copy.y = w.y;
      return copy;
   }
}