Welcome to the Instance Methods exercises! This topic focuses on understanding what instance methods are, how they work, and how to write effective methods for your classes.
- Understanding the difference between instance methods and static methods
- Writing methods that operate on object data (fields)
- Creating methods with different return types and parameters
- Using methods to encapsulate behavior and maintain object state
- Method naming conventions and best practices
You'll work with several classes to practice writing instance methods. Each exercise builds on the previous one, introducing new concepts and complexity.
Class: Calculator
Create a Calculator class with basic arithmetic methods that work with internal state.
Requirements:
- Fields:
double result(to store the current result) - Constructor: Initialize
resultto 0.0 - Methods:
add(double value)- Add value to resultsubtract(double value)- Subtract value from resultmultiply(double value)- Multiply result by valuedivide(double value)- Divide result by value (check for division by zero)getResult()- Return the current resultclear()- Reset result to 0.0
Class: TextProcessor
Create a class that processes text using various instance methods.
Requirements:
- Fields:
String text(the text to process) - Constructor: Takes initial text as parameter
- Methods:
setText(String newText)- Update the textgetText()- Return the current textgetLength()- Return length of texttoUpperCase()- Return text in uppercase (don't modify original)toLowerCase()- Return text in lowercase (don't modify original)reverse()- Return reversed textcontains(String substring)- Check if text contains substringgetWordCount()- Return number of words in text
Class: Counter
Create a counter class with methods that manage internal state.
Requirements:
- Fields:
int count,int step(increment/decrement amount) - Constructor: Takes initial count and step values
- Methods:
increment()- Increase count by stepdecrement()- Decrease count by stepreset()- Set count back to 0getCount()- Return current countsetStep(int newStep)- Change the step valuegetStep()- Return current step valueisPositive()- Return true if count > 0isNegative()- Return true if count < 0
Class: Temperature
Create a temperature class with conversion methods and validation.
Requirements:
- Fields:
double celsius(store temperature in Celsius) - Constructor: Takes temperature value and unit ("C", "F", or "K")
- Methods:
getCelsius()- Return temperature in CelsiusgetFahrenheit()- Return temperature in FahrenheitgetKelvin()- Return temperature in KelvinsetCelsius(double temp)- Set temperature in CelsiussetFahrenheit(double temp)- Set temperature in FahrenheitsetKelvin(double temp)- Set temperature in KelvinisFreezingWater()- Return true if water would freezeisBoilingWater()- Return true if water would boilgetTemperatureCategory()- Return "Cold", "Mild", "Hot", or "Extreme"
Class: ShoppingCart
Create a shopping cart that manages items and calculates totals.
Requirements:
- Fields:
ArrayList<String> items,ArrayList<Double> prices - Constructor: Initialize empty lists
- Methods:
addItem(String item, double price)- Add item with priceremoveItem(String item)- Remove first occurrence of item and its pricegetItemCount()- Return total number of itemscalculateTotal()- Return sum of all pricescalculateAverage()- Return average price per itemgetMostExpensive()- Return name of most expensive itemgetCheapest()- Return name of cheapest itemcontainsItem(String item)- Check if item exists in cartclear()- Remove all items
Class: BankAccount
Create a bank account with comprehensive transaction methods.
Requirements:
- Fields:
String accountNumber,double balance,ArrayList<String> transactionHistory - Constructor: Takes account number, sets balance to 0, initializes history
- Methods:
deposit(double amount)- Add money (validate amount > 0)withdraw(double amount)- Remove money if sufficient fundstransfer(BankAccount toAccount, double amount)- Transfer money to another accountgetBalance()- Return current balancegetAccountNumber()- Return account numbergetTransactionHistory()- Return copy of transaction historygetTransactionCount()- Return number of transactionshasInsufficientFunds(double amount)- Check if withdrawal would overdraftcalculateInterest(double rate)- Return interest amount for given rate
Class: StudentGradeBook
Create a grade book that manages student scores and calculations.
Requirements:
- Fields:
String studentName,ArrayList<Double> grades - Constructor: Takes student name, initializes empty grades list
- Methods:
addGrade(double grade)- Add grade (validate 0-100 range)removeLowestGrade()- Remove the lowest gradegetGradeCount()- Return number of gradescalculateAverage()- Return average of all gradesgetHighestGrade()- Return highest gradegetLowestGrade()- Return lowest gradegetLetterGrade()- Return letter grade based on averageisPassingGrade()- Return true if average >= 60getGradesSummary()- Return string with key statisticshasGradeAbove(double threshold)- Check if any grade exceeds threshold
- Open the
topic.jshfile - Find the class template for Exercise 1 (
Calculator) - Implement the required methods according to the specifications
- Run your code in jshell to test:
jshell topic.jsh - Verify all tests pass before moving to the next exercise
- Repeat for each exercise
- Instance methods operate on specific object instances and can access instance fields
- Methods should have clear, descriptive names that indicate what they do
- Return types should match what the method actually returns
- Parameter validation helps prevent errors and maintains data integrity
- Encapsulation means controlling access to object data through methods
- Methods can modify object state or return information about the object
Each class has test code at the bottom of the file. Make sure:
- All tests pass without errors
- Methods return the expected values
- Object state changes correctly when methods are called
- Validation works as expected (e.g., division by zero, invalid grades)
Good luck with your instance methods practice!