user677811
user677811

Reputation:

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.

Upvotes: 0

Views: 105

Answers (4)

Raze
Raze

Reputation: 2224

If Account implements Cloneable interface, you could also do

Account copy = oldAccount.clone();

Upvotes: 0

Mattias Cibien
Mattias Cibien

Reputation: 296

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

Upvotes: 0

Joseph Ottinger
Joseph Ottinger

Reputation: 4951

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.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

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.

Upvotes: 5

Related Questions