简体   繁体   中英

How can I make a new instance of an object in Java?

I am making a simple email application in Java. I have an Account class. Each Account class has a username and password attribute. I want to be able to create a new instance of the Account class from another class. How can I do this? It seems like it should be something very simple but I can't seem to figure it out.

If Account has a copy constructor , it's trivial:

Account newAccount = new Account(otherAccount);

If it does not, you can probably do something like

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

Obviously I just had to make up some of these method names and things, but you get the idea.

Account newAccount=new Account(username, password);

But surely there's more to the question than that...

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

That's going to create a copy of an old account without internal state...

Account cloneOfAccount=oldAccount.clone();

That will clone Account if it's cloneable, along with whatever state the clone() replicates...

Still not sure what aspect of the process is unclear.

You shoud use this code somewhere in the other class:

Account account = new Account();

However if you want that object to be called somewhere in the other class you should write something like:

public class Other {
   Account account;

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

If Account implements Cloneable interface, you could also do

Account copy = oldAccount.clone();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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