Oscar Lundberg Oscar Lundberg - 8 days ago 4x
Java Question

Class instances in console application

I'm working on a simple console application but i suddenly noticed a gap in my "knowledge" of classes.

I have a main java file and a separate class - "Account"

I wanted to create a new instance of account from a "Register Account" method. Without thinking about it i wrote the following and moved on.

Account newAcc = new Account();

But now I realize that i have no idea how to access the new Account or any further Account instances. Can anyone give me a pointer?


EDIT: more code

newAcc = new Account();
newAcc.name = "my name";
newAcc.balance = 0;

//Later i do this:
newAcc = new Account();
newAcc.name = "your name";
newAcc.balance = 1000;

Now I want to know "my" balance?


You need to store the two Account objects in different variables.

Account myAcc = new Account();
myAcc.name = "my name";
myAcc.balance = 0;

//Later i do this:
Account yourAcc = new Account();
yourAcc.name = "your name";
yourAcc.balance = 1000;

If you store them both in myAcc, when you create a new one the old one will be overwritten.