Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+13 votes
asked in CSC 305 Fall 2024 by (4.9k points)

2 Answers

+5 votes
 
Best answer

An example of encapsulation in Java is using private fields within a class and providing public getter and setter methods to control access to those fields. This ensures that the internal representation of an object is hidden from the outside world, allowing controlled access and modification of the data. Encapsulation helps maintain data integrity and simplifies code maintenance.

public class BankAccount {
private double balance;  // Private field to encapsulate the balance

// Constructor
public BankAccount(double initialBalance) {
    this.balance = initialBalance;
}

// Public getter method to access the balance
public double getBalance() {
    return balance;
}

// Public setter method to modify the balance
public void deposit(double amount) {
    if (amount > 0) {  // Validating input to maintain data integrity
        balance += amount;
    } else {
        System.out.println("Deposit amount must be positive.");
    }
}

public void withdraw(double amount) {
    if (amount > 0 && amount <= balance) {
        balance -= amount;
    } else {
        System.out.println("Insufficient funds or invalid amount.");
    }
}

}
Usage:

BankAccount account = new BankAccount(1000.0);
account.deposit(500.0);  
account.withdraw(300.0); 
System.out.println("Balance: " + account.getBalance()); // Accesses the balance'
answered by (4.4k points)
selected by
+2

Thank you that is very helpful!

0 votes

Encapsulation is the practice of bundling data and methods within a class and restricting direct access to some of its components. For example, in your Movie Tracker project, fields like title and genre in the Movie class are private, and public getters and setters control access.

answered ago by (2.1k points)
...