Search code examples
javaoopdata-persistence

How to ensure data persistence across classes and methods in Java?


I am new to Java and object oriented programming, hence this basic question.

Say for example I am developing a banking application. One of the objects is customer with some fields such as account balance, etc.

Assume there are some classes which provide some specific functionality. For example, there might be a discounts class which calculates discounts/cash-back refund, etc. based on some criterion. So this class modifies the account balance field of the customer object. Similarly there might be a penalty class which imposes penalty for, say, non-maintenance of minimum balance. So this class also modifies the account balance field of the customer object. There might be many such classes that modify the customer object.

My doubt is how is this implemented in Java? My idea is (and I am sure it is wrong) create a customer object in the discounts class and access the account balance field of customer object, as follows :

//This is in the Discounts class    
    Customer obj = new Customer("John");
    obj.accountbalance+ = discount;

Similarly to access the account balance field from penalty class, I do the same as follows :

//This is in the Penalty class
    Customer obj = new Customer("John"); 
    obj.accountbalance- = penalty;`

My question is about data persistence. How does a field such as account balance stay updated across all classes and methods? How does the data persist?

Am I right in creating Customer object in each class everytime I want to access the fields in Customer object. If not, what is the standard procedure in such cases.

Apologies once again for this basic question but this will benefit me and many Java beginners who might see this question later.


Solution

  • You're approaching it the wrong way. You should have one object for each Customer, and these Customers should have a field called accountBalance. Methods called discount() and penalty() (or something similar) should modify the accountBalance. To keep data (for persistence), you could write it to a file or something and read it across launches.