如何在Java中创建对象的新实例?

时间:2011-04-30 11:44:24

标签: java

我正在用Java制作一个简单的电子邮件应用程序。我有一个Account课程。每个Account类都有usernamepassword属性。我希望能够从另一个类创建Account类的新实例。我怎样才能做到这一点?看起来它应该是非常简单的东西,但我似乎无法弄明白。

4 个答案:

答案 0 :(得分:5)

如果Account复制构造函数,那就太简单了:

Account newAccount = new Account(otherAccount);

如果没有,你可能会做类似

的事情
String username = otherAccount.getUserName();
String password = otherAccount.getPassword();
Account newAccount = new Account(username, password);

显然,我只需要编写一些方法名称和内容,但你明白了。

答案 1 :(得分:2)

Account newAccount=new Account(username, password);

但肯定还有更多问题而不是......

Account copyOfAccount=new Account(oldAccount.getUsername(), 
   oldAccount.getPassword()); 

这将创建一个没有内部状态的旧帐户的副本......

Account cloneOfAccount=oldAccount.clone();

如果它可以克隆,那将克隆帐户,以及clone()复制的任何状态......

仍然不确定这个过程的哪个方面不清楚。

答案 2 :(得分:0)

您应该在其他类的某处使用此代码:

Account account = new Account();

但是如果你想在另一个类的某个地方调用该对象,你应该编写类似的东西:

public class Other {
   Account account;

   Other() {
       account = new Account();
   }
}

答案 3 :(得分:0)

如果Account实现Cloneable接口,您也可以

Account copy = oldAccount.clone();
相关问题