Bird
0
0

Which code correctly implements these instance methods?

hard📝 Application Q15 of 15
Java - Classes and Objects
You want to create a class BankAccount with an instance method deposit that adds money to the account balance, and another method getBalance that returns the current balance. Which code correctly implements these instance methods?
Aclass BankAccount { private double balance; void deposit(double amount) { balance += amount; } double getBalance() { return balance; } }
Bclass BankAccount { static double balance; void deposit(double amount) { balance += amount; } double getBalance() { return balance; } }
Cclass BankAccount { private double balance; static void deposit(double amount) { balance += amount; } static double getBalance() { return balance; } }
Dclass BankAccount { double balance; void deposit() { balance += amount; } double getBalance() { return balance; } }
Step-by-Step Solution
Solution:
  1. Step 1: Check instance variable and method signatures

    class BankAccount { private double balance; void deposit(double amount) { balance += amount; } double getBalance() { return balance; } } uses a private instance variable balance and instance methods that correctly update and return it.
  2. Step 2: Verify other options

    class BankAccount { static double balance; void deposit(double amount) { balance += amount; } double getBalance() { return balance; } } uses static variable, which shares balance across all accounts. class BankAccount { private double balance; static void deposit(double amount) { balance += amount; } static double getBalance() { return balance; } } uses static methods incorrectly. class BankAccount { double balance; void deposit() { balance += amount; } double getBalance() { return balance; } }'s deposit method lacks parameter amount.
  3. Final Answer:

    class BankAccount { private double balance; void deposit(double amount) { balance += amount; } double getBalance() { return balance; } } -> Option A
  4. Quick Check:

    Instance methods update and return object-specific data [OK]
Quick Trick: Instance methods use instance variables, not static, with parameters [OK]
Common Mistakes:
  • Using static variables for per-object data
  • Missing method parameters
  • Making instance methods static incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes