Objects and Methods: The Basics
Objects and Methods: The Basics
Here are beginner-friendly Java code examples focused on understanding objects and instance methods. These examples demonstrate how Java organizes code into classes and objects, showing the fundamental building blocks of object-oriented programming.
How to Read These Examples
- Start with the class structure - Understand what data the object holds
- Follow the constructor - See how objects are initialized
- Trace method calls - Follow how methods access and modify object state
- Notice encapsulation - See how data is protected and accessed through methods
- Practice object thinking - Understand how objects model real-world concepts
Example 1: Simple Student Object with Basic Methods
Code to Read:
1public class Student {
2 // Instance variables (fields) - each object has its own copy
3 private String name;
4 private int age;
5 private double gpa;
6 private boolean isEnrolled;
7
8 // Constructor - special method to create and initialize objects
9 public Student(String name, int age, double gpa) {
10 this.name = name; // 'this' refers to the current object
11 this.age = age;
12 this.gpa = gpa;
13 this.isEnrolled = true; // Default value
14 }
15
16 // Instance methods - operate on the object's data
17 public String getName() {
18 return name; // Access instance variable
19 }
20
21 public int getAge() {
22 return age;
23 }
24
25 public double getGpa() {
26 return gpa;
27 }
28
29 public boolean isEnrolled() {
30 return isEnrolled;
31 }
32
33 // Method that modifies object state
34 public void updateGpa(double newGpa) {
35 if (newGpa >= 0.0 && newGpa <= 4.0) {
36 this.gpa = newGpa;
37 }
38 }
39
40 // Method that changes enrollment status
41 public void withdraw() {
42 this.isEnrolled = false;
43 }
44
45 public void enroll() {
46 this.isEnrolled = true;
47 }
48
49 // Method that calculates and returns a value
50 public String getAcademicStatus() {
51 if (gpa >= 3.5) {
52 return "Dean's List";
53 } else if (gpa >= 3.0) {
54 return "Good Standing";
55 } else if (gpa >= 2.0) {
56 return "Probation";
57 } else {
58 return "Academic Warning";
59 }
60 }
61
62 // Method that returns formatted information
63 public String getDisplayInfo() {
64 String status = isEnrolled ? "Enrolled" : "Withdrawn";
65 return String.format("%s (Age: %d, GPA: %.2f, Status: %s)",
66 name, age, gpa, status);
67 }
68}
69
70// Class to demonstrate using the Student object
71public class StudentDemo {
72 public static void main(String[] args) {
73 // Creating objects using the constructor
74 Student alice = new Student("Alice Johnson", 20, 3.7);
75 Student bob = new Student("Bob Smith", 19, 2.8);
76
77 // Using getter methods to access object data
78 System.out.println("Student Name: " + alice.getName());
79 System.out.println("Alice's GPA: " + alice.getGpa());
80 System.out.println("Bob's Academic Status: " + bob.getAcademicStatus());
81
82 // Using methods that modify object state
83 alice.updateGpa(3.9);
84 bob.withdraw();
85
86 // Displaying updated information
87 System.out.println("After updates:");
88 System.out.println(alice.getDisplayInfo());
89 System.out.println(bob.getDisplayInfo());
90
91 // Each object maintains its own state
92 System.out.println("Alice enrolled? " + alice.isEnrolled()); // true
93 System.out.println("Bob enrolled? " + bob.isEnrolled()); // false
94 }
95}
What to Notice:
Details
- Private fields:
private String name;
- data is hidden inside the object - Each object has its own copy: Alice and Bob have separate
name
,age
,gpa
values this
keyword: Refers to the current object being operated on- Default values:
isEnrolled = true;
set in constructor
Details
- Special method: Same name as class, no return type
- Initialization: Sets up object’s initial state
- Parameters: Data needed to create a meaningful object
this.field = parameter
: Assigns parameter values to instance variables
Details
- Getters:
getName()
,getAge()
- provide controlled access to private data - Setters:
updateGpa()
- allow controlled modification with validation - Boolean getters:
isEnrolled()
- common pattern for boolean fields - Encapsulation: Outside code can’t directly access private fields
Trace Through Example:
1// Object creation and initialization:
2Student alice = new Student("Alice Johnson", 20, 3.7);
3// 1. New Student object created in memory
4// 2. Constructor called with parameters
5// 3. alice.name = "Alice Johnson"
6// 4. alice.age = 20
7// 5. alice.gpa = 3.7
8// 6. alice.isEnrolled = true
9
10// Method calls:
11alice.getName() // → returns "Alice Johnson"
12alice.getGpa() // → returns 3.7
13alice.getAcademicStatus() // → gpa (3.7) >= 3.5, so returns "Dean's List"
14
15// State modification:
16alice.updateGpa(3.9) // → alice.gpa changes from 3.7 to 3.9
Example 2: Bank Account with Balance Operations
Code to Read:
1public class BankAccount {
2 // Instance variables
3 private String accountNumber;
4 private String ownerName;
5 private double balance;
6 private boolean isActive;
7
8 // Constructor
9 public BankAccount(String accountNumber, String ownerName, double initialDeposit) {
10 this.accountNumber = accountNumber;
11 this.ownerName = ownerName;
12 this.balance = initialDeposit;
13 this.isActive = true;
14 }
15
16 // Getter methods
17 public String getAccountNumber() {
18 return accountNumber;
19 }
20
21 public String getOwnerName() {
22 return ownerName;
23 }
24
25 public double getBalance() {
26 return balance;
27 }
28
29 public boolean isActive() {
30 return isActive;
31 }
32
33 // Methods that modify account state
34 public boolean deposit(double amount) {
35 if (!isActive) {
36 System.out.println("Cannot deposit to inactive account");
37 return false;
38 }
39
40 if (amount <= 0) {
41 System.out.println("Deposit amount must be positive");
42 return false;
43 }
44
45 balance += amount;
46 System.out.printf("Deposited $%.2f. New balance: $%.2f%n", amount, balance);
47 return true;
48 }
49
50 public boolean withdraw(double amount) {
51 if (!isActive) {
52 System.out.println("Cannot withdraw from inactive account");
53 return false;
54 }
55
56 if (amount <= 0) {
57 System.out.println("Withdrawal amount must be positive");
58 return false;
59 }
60
61 if (amount > balance) {
62 System.out.println("Insufficient funds");
63 return false;
64 }
65
66 balance -= amount;
67 System.out.printf("Withdrew $%.2f. New balance: $%.2f%n", amount, balance);
68 return true;
69 }
70
71 public void closeAccount() {
72 isActive = false;
73 System.out.println("Account " + accountNumber + " has been closed");
74 }
75
76 public void reopenAccount() {
77 isActive = true;
78 System.out.println("Account " + accountNumber + " has been reopened");
79 }
80
81 // Method that calculates interest
82 public double calculateMonthlyInterest(double annualRate) {
83 double monthlyRate = annualRate / 12.0 / 100.0; // Convert to monthly decimal
84 return balance * monthlyRate;
85 }
86
87 // Method that applies interest to account
88 public void applyInterest(double annualRate) {
89 if (isActive && balance > 0) {
90 double interest = calculateMonthlyInterest(annualRate);
91 balance += interest;
92 System.out.printf("Applied interest: $%.2f. New balance: $%.2f%n",
93 interest, balance);
94 }
95 }
96
97 // Method that returns formatted account summary
98 public String getAccountSummary() {
99 String status = isActive ? "Active" : "Closed";
100 return String.format("Account: %s%nOwner: %s%nBalance: $%.2f%nStatus: %s",
101 accountNumber, ownerName, balance, status);
102 }
103}
104
105// Demonstration class
106public class BankingDemo {
107 public static void main(String[] args) {
108 // Create account objects
109 BankAccount checking = new BankAccount("CHK-001", "Alice Johnson", 1000.0);
110 BankAccount savings = new BankAccount("SAV-001", "Alice Johnson", 5000.0);
111
112 System.out.println("=== Initial Account Status ===");
113 System.out.println(checking.getAccountSummary());
114 System.out.println();
115 System.out.println(savings.getAccountSummary());
116 System.out.println();
117
118 // Perform transactions
119 System.out.println("=== Transactions ===");
120 checking.deposit(250.0);
121 checking.withdraw(150.0);
122 savings.applyInterest(2.5); // 2.5% annual interest
123
124 System.out.println();
125 System.out.println("=== Final Account Status ===");
126 System.out.println(checking.getAccountSummary());
127 System.out.println();
128 System.out.println(savings.getAccountSummary());
129
130 // Demonstrate object independence
131 checking.closeAccount();
132 System.out.println("Checking closed, but savings still active: " +
133 savings.isActive());
134 }
135}
What to Notice:
Details
- Private variables: Account data is encapsulated and protected
- State validation: Methods check
isActive
before allowing operations - State consistency: Balance is only modified through controlled methods
- Return values: Methods return
boolean
to indicate success/failure
Details
- Input validation:
amount <= 0
checks prevent invalid operations - Business rules: “Cannot withdraw more than balance” enforced in code
- Calculations: Interest calculation shows mathematical operations in methods
- Side effects: Methods both modify state AND provide user feedback
Details
- Separate instances:
checking
andsavings
are independent objects - Individual state: Closing one account doesn’t affect the other
- Method calls: Each object responds to the same method calls differently
- Data isolation: Alice’s checking account data is separate from savings data
Trace Through Example:
1// Object creation:
2BankAccount checking = new BankAccount("CHK-001", "Alice Johnson", 1000.0);
3// checking.accountNumber = "CHK-001"
4// checking.ownerName = "Alice Johnson"
5// checking.balance = 1000.0
6// checking.isActive = true
7
8// Method execution:
9checking.deposit(250.0);
10// 1. Check if (!isActive) → false, continue
11// 2. Check if (amount <= 0) → false, continue
12// 3. balance += amount → 1000.0 + 250.0 = 1250.0
13// 4. Print confirmation and return true
14
15checking.withdraw(150.0);
16// 1. Check if (!isActive) → false, continue
17// 2. Check if (amount <= 0) → false, continue
18// 3. Check if (amount > balance) → 150.0 > 1250.0 → false, continue
19// 4. balance -= amount → 1250.0 - 150.0 = 1100.0
20// 5. Print confirmation and return true
Example 3: Simple Book Object with Information Methods
Code to Read:
1public class Book {
2 // Instance variables
3 private String title;
4 private String author;
5 private int totalPages;
6 private int currentPage;
7 private boolean isFinished;
8
9 // Constructor
10 public Book(String title, String author, int totalPages) {
11 this.title = title;
12 this.author = author;
13 this.totalPages = totalPages;
14 this.currentPage = 0; // Start at beginning
15 this.isFinished = false; // Not finished initially
16 }
17
18 // Basic getter methods
19 public String getTitle() {
20 return title;
21 }
22
23 public String getAuthor() {
24 return author;
25 }
26
27 public int getTotalPages() {
28 return totalPages;
29 }
30
31 public int getCurrentPage() {
32 return currentPage;
33 }
34
35 public boolean isFinished() {
36 return isFinished;
37 }
38
39 // Methods that modify reading progress
40 public void readPages(int pages) {
41 if (pages <= 0) {
42 System.out.println("Must read at least 1 page");
43 return;
44 }
45
46 if (isFinished) {
47 System.out.println("Book is already finished!");
48 return;
49 }
50
51 currentPage += pages;
52
53 // Check if book is now finished
54 if (currentPage >= totalPages) {
55 currentPage = totalPages; // Don't go past the end
56 isFinished = true;
57 System.out.println("Congratulations! You finished the book!");
58 } else {
59 System.out.printf("Read %d pages. Now on page %d%n", pages, currentPage);
60 }
61 }
62
63 public void setBookmark(int page) {
64 if (page < 0 || page > totalPages) {
65 System.out.println("Invalid page number");
66 return;
67 }
68
69 currentPage = page;
70 isFinished = (currentPage >= totalPages);
71 System.out.printf("Bookmark set to page %d%n", page);
72 }
73
74 // Methods that calculate and return information
75 public int getPagesRemaining() {
76 if (isFinished) {
77 return 0;
78 }
79 return totalPages - currentPage;
80 }
81
82 public double getPercentageComplete() {
83 return ((double) currentPage / totalPages) * 100.0;
84 }
85
86 public String getProgressStatus() {
87 if (isFinished) {
88 return "Completed";
89 } else if (currentPage == 0) {
90 return "Not started";
91 } else if (getPercentageComplete() < 25.0) {
92 return "Just started";
93 } else if (getPercentageComplete() < 75.0) {
94 return "In progress";
95 } else {
96 return "Almost finished";
97 }
98 }
99
100 // Method that estimates reading time
101 public int getEstimatedMinutesRemaining(int pagesPerMinute) {
102 if (pagesPerMinute <= 0) {
103 return -1; // Invalid input
104 }
105 return getPagesRemaining() / pagesPerMinute;
106 }
107
108 // Method that returns formatted book information
109 public String getBookInfo() {
110 return String.format("'%s' by %s%nPages: %d/%d (%.1f%% complete)%nStatus: %s",
111 title, author, currentPage, totalPages,
112 getPercentageComplete(), getProgressStatus());
113 }
114}
115
116// Demo class
117public class ReadingDemo {
118 public static void main(String[] args) {
119 // Create book objects
120 Book novel = new Book("The Great Gatsby", "F. Scott Fitzgerald", 180);
121 Book textbook = new Book("Java Programming", "Author Name", 450);
122
123 System.out.println("=== New Books ===");
124 System.out.println(novel.getBookInfo());
125 System.out.println();
126 System.out.println(textbook.getBookInfo());
127 System.out.println();
128
129 // Simulate reading progress
130 System.out.println("=== Reading Session ===");
131 novel.readPages(45);
132 novel.readPages(60);
133 textbook.readPages(25);
134
135 System.out.println();
136 System.out.println("=== Updated Progress ===");
137 System.out.println(novel.getBookInfo());
138 System.out.printf("Estimated time remaining: %d minutes (reading 2 pages/min)%n",
139 novel.getEstimatedMinutesRemaining(2));
140 System.out.println();
141 System.out.println(textbook.getBookInfo());
142
143 // Finish one book
144 System.out.println();
145 System.out.println("=== Finishing Novel ===");
146 novel.readPages(100); // This should finish the book
147 System.out.println(novel.getBookInfo());
148 }
149}
What to Notice:
Details
- Multiple related fields:
currentPage
,isFinished
work together to track state - Automatic state updates:
isFinished
is updated whencurrentPage
reachestotalPages
- Boundary checking: Prevent reading past the end or setting invalid bookmarks
- Consistent state: Object maintains logical consistency between fields
Details
- Derived values:
getPagesRemaining()
calculates from existing data - Percentage calculations: Converting page numbers to completion percentage
- Status determination:
getProgressStatus()
uses percentage to determine reading stage - No stored calculated values: Calculations are performed when requested
Details
- Methods calling methods:
setBookmark()
calls logic similar toreadPages()
- Reusable calculations:
getPercentageComplete()
used bygetProgressStatus()
- Helper methods:
getPagesRemaining()
used bygetEstimatedMinutesRemaining()
- Consistent behavior: All methods respect the object’s state rules
Reading Practice Tips
After studying these object-oriented examples:
- Follow object lifecycles: Trace how objects are created, used, and modified
- Understand encapsulation: Notice how private fields are accessed only through methods
- Identify state changes: Track how method calls modify object state
- Recognize object independence: Each object maintains its own separate data
- Practice method tracing: Follow how methods call other methods within the same object
These patterns form the foundation of object-oriented programming in Java. Understanding how objects encapsulate data and behavior will help you read more complex Java code with confidence.