Mastering Java - Full Guide
Start Using Classes
Everything On ClassesWhen you need to store data for multiple entities (e.g., bank accounts), you might start out by using separate variables for each piece of information. For instance, if you want to store the name, account number, and account balance for three different accounts, you could do it like this:
// Bank Account 1
String name1 = "Alice";
int accountNumber1 = 1001;
double balance1 = 1500.00;
//Bank Account 2
String name2 = "Bob";
int accountNumber2 = 1002;
double balance2 = 2700.50;
// Bank Account 3
String name3 = "Charlie";
int accountNumber3 = 1003;
double balance3 = 3250.25;
// Print account information for each person
System.out.println("Name: " + name1 + ", Account Number: " + accountNumber1 + ", Balance: " + balance1);
System.out.println("Name: " + name2 + ", Account Number: " + accountNumber2 + ", Balance: " + balance2);
System.out.println("Name: " + name3 + ", Account Number: " + accountNumber3 + ", Balance: " + balance3);Why is This Messy?
Too Many Variables
You have three separate sets of variables that basically store the same type of data. As you add more accounts, you’d need even more variables (e.g.,name4,accountNumber4,balance4, etc.).No Logical Grouping
The data for each account is logically related, but right now it’s split across multiple variables. This makes your code harder to understand and maintain.Hard to Manage
If you want to add a method to deposit or withdraw money, you have no easy way to tie those actions to these three sets of variables. You’d end up writing more code to handle each account separately.
Let's create a fully functioning class called BankAccount that can be used to store the details for a person's bank account.
Class Definition
We'll start by making the class definition for BankAccount. A class in Java is like a blueprint. It groups together the data (fields) and the behavior (methods) for our bank account into a single, logical unit.
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 14 more lessons in Mastering Java - Full Guide.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.