Object-Oriented Basics
Encapsulation
Hiding Implementation
Your BankAccount class has a balance field. If it's public, anyone can set it
to negative values. Encapsulation makes fields private and provides methods that
validate changes - protecting your data from misuse.
Private fields
Hide internal data from direct access.
public class PrivateFields {
public static void main(String[] args) {
System.out.println("=== Private Fields ===\n");
// Create a bank account
BankAccount account = new BankAccount("John Doe", 1000);
// Can't access private fields directly!
// System.out.println(account.balance); // Compile error!
// account.balance = 1000000; // Compile error!
// Must use methods
System.out.println("Account holder: " + account.getOwner());
System.out.println("Balance: $" + account.getBalance());
// Change balance through method
account.deposit(500);
System.out.println("After deposit: $" + account.getBalance());
// This would have been possible without private:
// account.balance = -1000000; // Steal money!
// account.owner = ""; // Remove owner!
System.out.println("\n=== Why Private? ===");
System.out.println("✓ Can't set invalid balance");
System.out.println("✓ Can't bypass business rules");
System.out.println("✓ Implementation can change safely");
}
}
class BankAccount {
private String owner;
private double balance;
BankAccount(String owner, double initialBalance) {
this.owner = owner;
this.balance = Math.max(0, initialBalance); // Ensure non-negative
}
// Public methods to access private data
public String getOwner() {
return owner;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited $" + amount);
} else {
System.out.println("Invalid deposit amount");
}
}
}
public static void main(String[] args)
1public class PrivateFields {2 public static void main(String[] args) {3 System.out.println("=== Private Fields ===\n");4 5 // Create a bank account //?create6 BankAccount account = new BankAccount("John Doe", 1000);output=== Private Fields ===this.owner ← John Doe, this.balance ← 1000.0, account ← ⟨BankAccount A⟩
5 // Create a bank account //?create6 BankAccount account→ ⟨BankAccount A⟩ = new BankAccount("John Doe", 1000);7 8 // Can't access private fields directly! //?noaccess9 // System.out.println(account.balance); // Compile error!10 // account.balance = 1000000; // Compile error!11 12 // Must use methods //?usemethods13 System.out.println("Account holder: " + account.getOwner());14 System.out.println("Balance: $" + account.getBalance());15 16 // Change balance through method17 account.deposit(500);18 System.out.println("After deposit: $" + account.getBalance());19 20 // This would have been possible without private:21 // account.balance = -1000000; // Steal money!22 // account.owner = ""; // Remove owner!23 24 System.out.println("\n=== Why Private? ===");25 System.out.println("✓ Can't set invalid balance");26 System.out.println("✓ Can't bypass business rules");27 System.out.println("✓ Implementation can change safely");28 }29}3031class BankAccount {32 private String owner; //?private33 private double balance;34 35 BankAccount(String ownerJohn Doe, double initialBalance1000.0) {36 this.owner→ John Doe = ownerJohn Doe;37 this.balance→ 1000.0 = Math.max(0, initialBalance1000.0); // Ensure non-negative38 }public String getOwner()
40// Public methods to access private data //?accessors41public String getOwner() {42 return ownerJohn Doe;43}System.out.println("Account holder: " + account.getOwner());
12// Must use methods //?usemethods13System.out.println("Account holder: " + account.getOwner());14System.out.println("Balance: $" + account.getBalance());outputAccount holder: John Doepublic double getBalance()
pass 1 of 245public double getBalance() {46 return balance1000.0;47}System.out.println("Balance: $" + account.getBalance());
13System.out.println("Account holder: " + account.getOwner());14System.out.println("Balance: $" + account.getBalance());1516// Change balance through method17account.deposit(500);18System.out.println("After deposit: $" + account.getBalance());outputBalance: $1000.0public void deposit(double amount)
49public void deposit(double amount500.0) { //?deposit50 if (amount > 0) {balance ← 1500.0
16 // Change balance through method17 account.deposit(500);18 System.out.println("After deposit: $" + account.getBalance());19 20 // This would have been possible without private:21 // account.balance = -1000000; // Steal money!22 // account.owner = ""; // Remove owner!23 24 System.out.println("\n=== Why Private? ===");25 System.out.println("✓ Can't set invalid balance");26 System.out.println("✓ Can't bypass business rules");27 System.out.println("✓ Implementation can change safely");28 }29}3031class BankAccount {32 private String owner; //?private33 private double balance;34 35 BankAccount(String owner, double initialBalance) {36 this.owner = owner;37 this.balance = Math.max(0, initialBalance); // Ensure non-negative38 }39 40 // Public methods to access private data //?accessors41 public String getOwner() {42 return owner;43 }44 45 public double getBalance() {46 return balance;47 }48 49 public void deposit(double amount) { //?deposit50 if (amount500.0 > 0) {51 balance→ 1500.0 += amount500.0;52 System.out.println("Deposited $" + amount500.0);53 } else {outputDeposited $500.0public double getBalance()
pass 2 of 245public double getBalance() {46 return balance1500.0;47}System.out.println("After deposit: $" + account.getBalance());
17 account.deposit(500);18 System.out.println("After deposit: $" + account.getBalance());19 20 // This would have been possible without private:21 // account.balance = -1000000; // Steal money!22 // account.owner = ""; // Remove owner!23 24 System.out.println("\n=== Why Private? ===");25 System.out.println("✓ Can't set invalid balance");26 System.out.println("✓ Can't bypass business rules");27 System.out.println("✓ Implementation can change safely");28}outputAfter deposit: $1500.0 === Why Private? === ✓ Can't set invalid balance ✓ Can't bypass business rules ✓ Implementation can change safely
private makes fields inaccessible from outside the class.
Getter methods
Provide read access to private fields.
public class Getters {
public static void main(String[] args) {
System.out.println("=== Getter Methods ===\n");
Person person = new Person("Alice", "Smith", 30);
// Access data through getters
System.out.println("First name: " + person.getFirstName());
System.out.println("Last name: " + person.getLastName());
System.out.println("Age: " + person.getAge());
// Computed getter
System.out.println("Full name: " + person.getFullName());
// Boolean getter uses 'is' prefix
System.out.println("Is adult: " + person.isAdult());
System.out.println("\n=== Naming Convention ===");
System.out.println("getXxx() - for regular types");
System.out.println("isXxx() - for boolean types");
}
}
class Person {
private String firstName;
private String lastName;
private int age;
Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
// Standard getters
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
// Computed property - not stored, calculated
public String getFullName() {
return firstName + " " + lastName;
}
// Boolean getter uses 'is' prefix
public boolean isAdult() {
return age >= 18;
}
}
public static void main(String[] args)
1public class Getters {2 public static void main(String[] args) {3 System.out.println("=== Getter Methods ===\n");4 5 Person person = new Person("Alice", "Smith", 30); //?createoutput=== Getter Methods ===this.firstName ← Alice, this.lastName ← Smith, this.age ← 30, person ← ⟨Person A⟩
5 Person person→ ⟨Person A⟩ = new Person("Alice", "Smith", 30); //?create6 7 // Access data through getters //?getters8 System.out.println("First name: " + person.getFirstName());9 System.out.println("Last name: " + person.getLastName());10 System.out.println("Age: " + person.getAge());11 12 // Computed getter //?computed13 System.out.println("Full name: " + person.getFullName());14 15 // Boolean getter uses 'is' prefix //?is16 System.out.println("Is adult: " + person.isAdult());17 18 System.out.println("\n=== Naming Convention ===");19 System.out.println("getXxx() - for regular types");20 System.out.println("isXxx() - for boolean types");21 }22}2324class Person {25 private String firstName; //?fields26 private String lastName;27 private int age;28 29 Person(String firstNameAlice, String lastNameSmith, int age30) {30 this.firstName→ Alice = firstNameAlice;31 this.lastName→ Smith = lastNameSmith;32 this.age→ 30 = age30;33 }public String getFirstName()
35// Standard getters //?standard36public String getFirstName() {37 return firstNameAlice;38}System.out.println("First name: " + person.getFirstName());
7// Access data through getters //?getters8System.out.println("First name: " + person.getFirstName());9System.out.println("Last name: " + person.getLastName());10System.out.println("Age: " + person.getAge());outputFirst name: Alicepublic String getLastName()
40public String getLastName() {41 return lastNameSmith;42}System.out.println("Last name: " + person.getLastName());
8System.out.println("First name: " + person.getFirstName());9System.out.println("Last name: " + person.getLastName());10System.out.println("Age: " + person.getAge());outputLast name: Smithpublic int getAge()
44public int getAge() {45 return age30;46}System.out.println("Age: " + person.getAge());
9System.out.println("Last name: " + person.getLastName());10System.out.println("Age: " + person.getAge());1112// Computed getter //?computed13System.out.println("Full name: " + person.getFullName());outputAge: 30public String getFullName()
48// Computed property - not stored, calculated //?computedmethod49public String getFullName() {50 return firstNameAlice + " " + lastNameSmith;51}System.out.println("Full name: " + person.getFullName());
12// Computed getter //?computed13System.out.println("Full name: " + person.getFullName());1415// Boolean getter uses 'is' prefix //?is16System.out.println("Is adult: " + person.isAdult());outputFull name: Alice Smithpublic boolean isAdult()
53// Boolean getter uses 'is' prefix //?ismethod54public boolean isAdult() {55 return age30 >= 18;56}System.out.println("Is adult: " + person.isAdult());
15 // Boolean getter uses 'is' prefix //?is16 System.out.println("Is adult: " + person.isAdult());17 18 System.out.println("\n=== Naming Convention ===");19 System.out.println("getXxx() - for regular types");20 System.out.println("isXxx() - for boolean types");21}outputIs adult: true === Naming Convention === getXxx() - for regular types isXxx() - for boolean types
Getters return field values. Convention: getFieldName().
Setter methods with validation
Control how fields are modified.
public class SettersValidation {
public static void main(String[] args) {
System.out.println("=== Setters with Validation ===\n");
double initialPrice = 999.99;
double newPrice = 899.99;
int newStock = 5;
Product product = new Product("Laptop", initialPrice, 10);
System.out.println("Initial: " + product.describe());
// Valid updates
product.setPrice(newPrice);
System.out.println("Price updated: " + product.describe());
product.setStock(newStock);
System.out.println("Stock updated: " + product.describe());
// Invalid updates - rejected!
System.out.println("\n=== Invalid Attempts ===");
product.setPrice(-100); // Rejected
System.out.println("After negative price: " + product.describe());
product.setStock(-5); // Rejected
System.out.println("After negative stock: " + product.describe());
product.setName(""); // Rejected
System.out.println("After empty name: " + product.describe());
System.out.println("\n=== Values Unchanged ===");
System.out.println("Invalid values were rejected!");
}
}
class Product {
private String name;
private double price;
private int stock;
Product(String name, double price, int stock) {
// Use setters for validation even in constructor!
setName(name);
setPrice(price);
setStock(stock);
}
// Getter for name
public String getName() {
return name;
}
// Setter with validation
public void setName(String name) {
if (name == null || name.isBlank()) {
System.out.println(" [Rejected: name cannot be blank]");
return;
}
this.name = name;
}
public double getPrice() {
return price;
}
// Setter with validation
public void setPrice(double price) {
if (price < 0) {
System.out.println(" [Rejected: price cannot be negative]");
return;
}
this.price = price;
}
public int getStock() {
return stock;
}
// Setter with validation
public void setStock(int stock) {
if (stock < 0) {
System.out.println(" [Rejected: stock cannot be negative]");
return;
}
this.stock = stock;
}
String describe() {
return name + " - $" + price + " (" + stock + " in stock)";
}
}
public class SettersValidation {
public static void main(String[] args) {
System.out.println("=== Setters with Validation ===\n");
double initialPrice = 499.50;
double newPrice = 899.99;
int newStock = 5;
Product product = new Product("Laptop", initialPrice, 10);
System.out.println("Initial: " + product.describe());
// Valid updates
product.setPrice(newPrice);
System.out.println("Price updated: " + product.describe());
product.setStock(newStock);
System.out.println("Stock updated: " + product.describe());
// Invalid updates - rejected!
System.out.println("\n=== Invalid Attempts ===");
product.setPrice(-100); // Rejected
System.out.println("After negative price: " + product.describe());
product.setStock(-5); // Rejected
System.out.println("After negative stock: " + product.describe());
product.setName(""); // Rejected
System.out.println("After empty name: " + product.describe());
System.out.println("\n=== Values Unchanged ===");
System.out.println("Invalid values were rejected!");
}
}
class Product {
private String name;
private double price;
private int stock;
Product(String name, double price, int stock) {
// Use setters for validation even in constructor!
setName(name);
setPrice(price);
setStock(stock);
}
// Getter for name
public String getName() {
return name;
}
// Setter with validation
public void setName(String name) {
if (name == null || name.isBlank()) {
System.out.println(" [Rejected: name cannot be blank]");
return;
}
this.name = name;
}
public double getPrice() {
return price;
}
// Setter with validation
public void setPrice(double price) {
if (price < 0) {
System.out.println(" [Rejected: price cannot be negative]");
return;
}
this.price = price;
}
public int getStock() {
return stock;
}
// Setter with validation
public void setStock(int stock) {
if (stock < 0) {
System.out.println(" [Rejected: stock cannot be negative]");
return;
}
this.stock = stock;
}
String describe() {
return name + " - $" + price + " (" + stock + " in stock)";
}
}
public class SettersValidation {
public static void main(String[] args) {
System.out.println("=== Setters with Validation ===\n");
double initialPrice = 1299.00;
double newPrice = 899.99;
int newStock = 5;
Product product = new Product("Laptop", initialPrice, 10);
System.out.println("Initial: " + product.describe());
// Valid updates
product.setPrice(newPrice);
System.out.println("Price updated: " + product.describe());
product.setStock(newStock);
System.out.println("Stock updated: " + product.describe());
// Invalid updates - rejected!
System.out.println("\n=== Invalid Attempts ===");
product.setPrice(-100); // Rejected
System.out.println("After negative price: " + product.describe());
product.setStock(-5); // Rejected
System.out.println("After negative stock: " + product.describe());
product.setName(""); // Rejected
System.out.println("After empty name: " + product.describe());
System.out.println("\n=== Values Unchanged ===");
System.out.println("Invalid values were rejected!");
}
}
class Product {
private String name;
private double price;
private int stock;
Product(String name, double price, int stock) {
// Use setters for validation even in constructor!
setName(name);
setPrice(price);
setStock(stock);
}
// Getter for name
public String getName() {
return name;
}
// Setter with validation
public void setName(String name) {
if (name == null || name.isBlank()) {
System.out.println(" [Rejected: name cannot be blank]");
return;
}
this.name = name;
}
public double getPrice() {
return price;
}
// Setter with validation
public void setPrice(double price) {
if (price < 0) {
System.out.println(" [Rejected: price cannot be negative]");
return;
}
this.price = price;
}
public int getStock() {
return stock;
}
// Setter with validation
public void setStock(int stock) {
if (stock < 0) {
System.out.println(" [Rejected: stock cannot be negative]");
return;
}
this.stock = stock;
}
String describe() {
return name + " - $" + price + " (" + stock + " in stock)";
}
}
public class SettersValidation {
public static void main(String[] args) {
System.out.println("=== Setters with Validation ===\n");
double initialPrice = 999.99;
double newPrice = 749.99;
int newStock = 5;
Product product = new Product("Laptop", initialPrice, 10);
System.out.println("Initial: " + product.describe());
// Valid updates
product.setPrice(newPrice);
System.out.println("Price updated: " + product.describe());
product.setStock(newStock);
System.out.println("Stock updated: " + product.describe());
// Invalid updates - rejected!
System.out.println("\n=== Invalid Attempts ===");
product.setPrice(-100); // Rejected
System.out.println("After negative price: " + product.describe());
product.setStock(-5); // Rejected
System.out.println("After negative stock: " + product.describe());
product.setName(""); // Rejected
System.out.println("After empty name: " + product.describe());
System.out.println("\n=== Values Unchanged ===");
System.out.println("Invalid values were rejected!");
}
}
class Product {
private String name;
private double price;
private int stock;
Product(String name, double price, int stock) {
// Use setters for validation even in constructor!
setName(name);
setPrice(price);
setStock(stock);
}
// Getter for name
public String getName() {
return name;
}
// Setter with validation
public void setName(String name) {
if (name == null || name.isBlank()) {
System.out.println(" [Rejected: name cannot be blank]");
return;
}
this.name = name;
}
public double getPrice() {
return price;
}
// Setter with validation
public void setPrice(double price) {
if (price < 0) {
System.out.println(" [Rejected: price cannot be negative]");
return;
}
this.price = price;
}
public int getStock() {
return stock;
}
// Setter with validation
public void setStock(int stock) {
if (stock < 0) {
System.out.println(" [Rejected: stock cannot be negative]");
return;
}
this.stock = stock;
}
String describe() {
return name + " - $" + price + " (" + stock + " in stock)";
}
}
public class SettersValidation {
public static void main(String[] args) {
System.out.println("=== Setters with Validation ===\n");
double initialPrice = 999.99;
double newPrice = 1099.99;
int newStock = 5;
Product product = new Product("Laptop", initialPrice, 10);
System.out.println("Initial: " + product.describe());
// Valid updates
product.setPrice(newPrice);
System.out.println("Price updated: " + product.describe());
product.setStock(newStock);
System.out.println("Stock updated: " + product.describe());
// Invalid updates - rejected!
System.out.println("\n=== Invalid Attempts ===");
product.setPrice(-100); // Rejected
System.out.println("After negative price: " + product.describe());
product.setStock(-5); // Rejected
System.out.println("After negative stock: " + product.describe());
product.setName(""); // Rejected
System.out.println("After empty name: " + product.describe());
System.out.println("\n=== Values Unchanged ===");
System.out.println("Invalid values were rejected!");
}
}
class Product {
private String name;
private double price;
private int stock;
Product(String name, double price, int stock) {
// Use setters for validation even in constructor!
setName(name);
setPrice(price);
setStock(stock);
}
// Getter for name
public String getName() {
return name;
}
// Setter with validation
public void setName(String name) {
if (name == null || name.isBlank()) {
System.out.println(" [Rejected: name cannot be blank]");
return;
}
this.name = name;
}
public double getPrice() {
return price;
}
// Setter with validation
public void setPrice(double price) {
if (price < 0) {
System.out.println(" [Rejected: price cannot be negative]");
return;
}
this.price = price;
}
public int getStock() {
return stock;
}
// Setter with validation
public void setStock(int stock) {
if (stock < 0) {
System.out.println(" [Rejected: stock cannot be negative]");
return;
}
this.stock = stock;
}
String describe() {
return name + " - $" + price + " (" + stock + " in stock)";
}
}
public class SettersValidation {
public static void main(String[] args) {
System.out.println("=== Setters with Validation ===\n");
double initialPrice = 999.99;
double newPrice = 899.99;
int newStock = 0;
Product product = new Product("Laptop", initialPrice, 10);
System.out.println("Initial: " + product.describe());
// Valid updates
product.setPrice(newPrice);
System.out.println("Price updated: " + product.describe());
product.setStock(newStock);
System.out.println("Stock updated: " + product.describe());
// Invalid updates - rejected!
System.out.println("\n=== Invalid Attempts ===");
product.setPrice(-100); // Rejected
System.out.println("After negative price: " + product.describe());
product.setStock(-5); // Rejected
System.out.println("After negative stock: " + product.describe());
product.setName(""); // Rejected
System.out.println("After empty name: " + product.describe());
System.out.println("\n=== Values Unchanged ===");
System.out.println("Invalid values were rejected!");
}
}
class Product {
private String name;
private double price;
private int stock;
Product(String name, double price, int stock) {
// Use setters for validation even in constructor!
setName(name);
setPrice(price);
setStock(stock);
}
// Getter for name
public String getName() {
return name;
}
// Setter with validation
public void setName(String name) {
if (name == null || name.isBlank()) {
System.out.println(" [Rejected: name cannot be blank]");
return;
}
this.name = name;
}
public double getPrice() {
return price;
}
// Setter with validation
public void setPrice(double price) {
if (price < 0) {
System.out.println(" [Rejected: price cannot be negative]");
return;
}
this.price = price;
}
public int getStock() {
return stock;
}
// Setter with validation
public void setStock(int stock) {
if (stock < 0) {
System.out.println(" [Rejected: stock cannot be negative]");
return;
}
this.stock = stock;
}
String describe() {
return name + " - $" + price + " (" + stock + " in stock)";
}
}
public class SettersValidation {
public static void main(String[] args) {
System.out.println("=== Setters with Validation ===\n");
double initialPrice = 999.99;
double newPrice = 899.99;
int newStock = 25;
Product product = new Product("Laptop", initialPrice, 10);
System.out.println("Initial: " + product.describe());
// Valid updates
product.setPrice(newPrice);
System.out.println("Price updated: " + product.describe());
product.setStock(newStock);
System.out.println("Stock updated: " + product.describe());
// Invalid updates - rejected!
System.out.println("\n=== Invalid Attempts ===");
product.setPrice(-100); // Rejected
System.out.println("After negative price: " + product.describe());
product.setStock(-5); // Rejected
System.out.println("After negative stock: " + product.describe());
product.setName(""); // Rejected
System.out.println("After empty name: " + product.describe());
System.out.println("\n=== Values Unchanged ===");
System.out.println("Invalid values were rejected!");
}
}
class Product {
private String name;
private double price;
private int stock;
Product(String name, double price, int stock) {
// Use setters for validation even in constructor!
setName(name);
setPrice(price);
setStock(stock);
}
// Getter for name
public String getName() {
return name;
}
// Setter with validation
public void setName(String name) {
if (name == null || name.isBlank()) {
System.out.println(" [Rejected: name cannot be blank]");
return;
}
this.name = name;
}
public double getPrice() {
return price;
}
// Setter with validation
public void setPrice(double price) {
if (price < 0) {
System.out.println(" [Rejected: price cannot be negative]");
return;
}
this.price = price;
}
public int getStock() {
return stock;
}
// Setter with validation
public void setStock(int stock) {
if (stock < 0) {
System.out.println(" [Rejected: stock cannot be negative]");
return;
}
this.stock = stock;
}
String describe() {
return name + " - $" + price + " (" + stock + " in stock)";
}
}
initialPrice ← 999.99, newPrice ← 899.99, newStock ← 5
1public class SettersValidation {2 public static void main(String[] args) {3 System.out.println("=== Setters with Validation ===\n");4 5 double initialPrice→ 999.99 = 999.99; //@initialPrice=499.50, 1299.006 double newPrice→ 899.99 = 899.99; //@newPrice=749.99, 1099.997 int newStock→ 5 = 5; //@newStock=0, 258 Product product = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());output=== Setters with Validation ===Product(String name, double price, int stock)
40Product(String nameLaptop, double price999.99, int stock10) {41 // Use setters for validation even in constructor! //?usesetter42 setName(nameLaptop);43 setPrice(price);this.name ← Laptop
pass 1 of 241 // Use setters for validation even in constructor! //?usesetter42 setName(nameLaptop);43 setPrice(price999.99);44 setStock(stock);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation //?setname53public void setName(String nameLaptop) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name→ Laptop = nameLaptop;59}this.price ← 999.99
pass 1 of 342 setName(name);43 setPrice(price999.99);44 setStock(stock10);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation //?setname53public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59}6061public double getPrice() {62 return price;63}6465// Setter with validation //?setprice66public void setPrice(double price999.99) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price→ 999.99 = price999.99;72}All 3 passes — pass 1 is the card above pass pricestocknewPricethis.price1 999.99 10 — 999.99 2 899.99 — 899.99 899.99 3 -100.0 — — — this.stock ← 10, product ← ⟨Product A⟩
pass 1 of 37 int newStock = 5; //@newStock=0, 258 Product product→ ⟨Product A⟩ = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());10 11 // Valid updates //?valid12 product.setPrice(newPrice);13 System.out.println("Price updated: " + product.describe());14 15 product.setStock(newStock);16 System.out.println("Stock updated: " + product.describe());17 18 // Invalid updates - rejected! //?invalid19 System.out.println("\n=== Invalid Attempts ===");20 21 product.setPrice(-100); // Rejected22 System.out.println("After negative price: " + product.describe());23 24 product.setStock(-5); // Rejected 25 System.out.println("After negative stock: " + product.describe());26 27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32 }33}3435class Product {36 private String name;37 private double price;38 private int stock;39 40 Product(String name, double price, int stock) {41 // Use setters for validation even in constructor! //?usesetter42 setName(name);43 setPrice(price);44 setStock(stock10);45 }46 47 // Getter for name48 public String getName() {49 return name;50 }51 52 // Setter with validation //?setname53 public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59 }60 61 public double getPrice() {62 return price;63 }64 65 // Setter with validation //?setprice66 public void setPrice(double price) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price = price;72 }73 74 public int getStock() {75 return stock;76 }77 78 // Setter with validation //?setstock79 public void setStock(int stock10) {80 if (stock < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }84 this.stock→ 10 = stock10;85 }All 3 passes — pass 1 is the card above pass stocknewStockthis.stockproduct1 10 — 10 ⟨Product A⟩ 2 5 5 5 — 3 -5 — — — String describe()
pass 1 of 687String describe() {88 return nameLaptop + " - $" + price999.99 + " (" + stock10 + " in stock)";89}All 6 passes — pass 1 is the card above pass pricestock1 999.99 10 2 899.99 10 3 899.99 5 4 899.99 5 5 899.99 5 6 899.99 5 product.setPrice(newPrice);
8Product product = new Product("Laptop", initialPrice, 10);9System.out.println("Initial: " + product.describe());1011// Valid updates //?valid12product.setPrice(newPrice899.99);13System.out.println("Price updated: " + product.describe());outputInitial: Laptop - $999.99 (10 in stock)product.setStock(newStock);
12product.setPrice(newPrice);13System.out.println("Price updated: " + product.describe());1415product.setStock(newStock5);16System.out.println("Stock updated: " + product.describe());outputPrice updated: Laptop - $899.99 (10 in stock)System.out.println("Stock updated: " + product.describe());
15product.setStock(newStock);16System.out.println("Stock updated: " + product.describe());1718// Invalid updates - rejected! //?invalid19System.out.println("\n=== Invalid Attempts ===");2021product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());outputStock updated: Laptop - $899.99 (5 in stock) === Invalid Attempts ===if (price < 0)
66public void setPrice(double price) {67 if (price-100.0 < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }output [Rejected: price cannot be negative]product.setPrice(-100); // Rejected
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());System.out.println("After negative price: " + product.describe());
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());2324product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());outputAfter negative price: Laptop - $899.99 (5 in stock)if (stock < 0)
79public void setStock(int stock) {80 if (stock-5 < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }output [Rejected: stock cannot be negative]product.setStock(-5); // Rejected
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());System.out.println("After negative stock: " + product.describe());
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());2627product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());outputAfter negative stock: Laptop - $899.99 (5 in stock)public void setName(String name)
pass 2 of 252// Setter with validation //?setname53public void setName(String name(empty)) {54 if (name == null || name.isBlank()) {if (name == null || name.isBlank())
53public void setName(String name) {54 if (name(empty) == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }output [Rejected: name cannot be blank]product.setName(""); // Rejected
27product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());System.out.println("After empty name: " + product.describe());
27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32}outputAfter empty name: Laptop - $899.99 (5 in stock) === Values Unchanged === Invalid values were rejected!
initialPrice ← 499.5, newPrice ← 899.99, newStock ← 5
1public class SettersValidation {2 public static void main(String[] args) {3 System.out.println("=== Setters with Validation ===\n");4 5 double initialPrice→ 499.5 = 499.50;6 double newPrice→ 899.99 = 899.99;7 int newStock→ 5 = 5;8 Product product = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());output=== Setters with Validation ===Product(String name, double price, int stock)
40Product(String nameLaptop, double price499.5, int stock10) {41 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price);this.name ← Laptop
pass 1 of 241 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price499.5);44 setStock(stock);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String nameLaptop) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name→ Laptop = nameLaptop;59}this.price ← 499.5
pass 1 of 342 setName(name);43 setPrice(price499.5);44 setStock(stock10);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59}6061public double getPrice() {62 return price;63}6465// Setter with validation66public void setPrice(double price499.5) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price→ 499.5 = price499.5;72}All 3 passes — pass 1 is the card above pass pricestocknewPricethis.price1 499.5 10 — 499.5 2 899.99 — 899.99 899.99 3 -100.0 — — — this.stock ← 10, product ← ⟨Product A⟩
pass 1 of 37 int newStock = 5;8 Product product→ ⟨Product A⟩ = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());10 11 // Valid updates12 product.setPrice(newPrice);13 System.out.println("Price updated: " + product.describe());14 15 product.setStock(newStock);16 System.out.println("Stock updated: " + product.describe());17 18 // Invalid updates - rejected!19 System.out.println("\n=== Invalid Attempts ===");20 21 product.setPrice(-100); // Rejected22 System.out.println("After negative price: " + product.describe());23 24 product.setStock(-5); // Rejected 25 System.out.println("After negative stock: " + product.describe());26 27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32 }33}3435class Product {36 private String name;37 private double price;38 private int stock;39 40 Product(String name, double price, int stock) {41 // Use setters for validation even in constructor!42 setName(name);43 setPrice(price);44 setStock(stock10);45 }46 47 // Getter for name48 public String getName() {49 return name;50 }51 52 // Setter with validation53 public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59 }60 61 public double getPrice() {62 return price;63 }64 65 // Setter with validation66 public void setPrice(double price) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price = price;72 }73 74 public int getStock() {75 return stock;76 }77 78 // Setter with validation79 public void setStock(int stock10) {80 if (stock < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }84 this.stock→ 10 = stock10;85 }All 3 passes — pass 1 is the card above pass stocknewStockthis.stockproduct1 10 — 10 ⟨Product A⟩ 2 5 5 5 — 3 -5 — — — String describe()
pass 1 of 687String describe() {88 return nameLaptop + " - $" + price499.5 + " (" + stock10 + " in stock)";89}All 6 passes — pass 1 is the card above pass pricestock1 499.5 10 2 899.99 10 3 899.99 5 4 899.99 5 5 899.99 5 6 899.99 5 product.setPrice(newPrice);
8Product product = new Product("Laptop", initialPrice, 10);9System.out.println("Initial: " + product.describe());1011// Valid updates12product.setPrice(newPrice899.99);13System.out.println("Price updated: " + product.describe());outputInitial: Laptop - $499.5 (10 in stock)product.setStock(newStock);
12product.setPrice(newPrice);13System.out.println("Price updated: " + product.describe());1415product.setStock(newStock5);16System.out.println("Stock updated: " + product.describe());outputPrice updated: Laptop - $899.99 (10 in stock)System.out.println("Stock updated: " + product.describe());
15product.setStock(newStock);16System.out.println("Stock updated: " + product.describe());1718// Invalid updates - rejected!19System.out.println("\n=== Invalid Attempts ===");2021product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());outputStock updated: Laptop - $899.99 (5 in stock) === Invalid Attempts ===if (price < 0)
66public void setPrice(double price) {67 if (price-100.0 < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }output [Rejected: price cannot be negative]product.setPrice(-100); // Rejected
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());System.out.println("After negative price: " + product.describe());
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());2324product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());outputAfter negative price: Laptop - $899.99 (5 in stock)if (stock < 0)
79public void setStock(int stock) {80 if (stock-5 < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }output [Rejected: stock cannot be negative]product.setStock(-5); // Rejected
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());System.out.println("After negative stock: " + product.describe());
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());2627product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());outputAfter negative stock: Laptop - $899.99 (5 in stock)public void setName(String name)
pass 2 of 252// Setter with validation53public void setName(String name(empty)) {54 if (name == null || name.isBlank()) {if (name == null || name.isBlank())
53public void setName(String name) {54 if (name(empty) == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }output [Rejected: name cannot be blank]product.setName(""); // Rejected
27product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());System.out.println("After empty name: " + product.describe());
27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32}outputAfter empty name: Laptop - $899.99 (5 in stock) === Values Unchanged === Invalid values were rejected!
initialPrice ← 1299.0, newPrice ← 899.99, newStock ← 5
1public class SettersValidation {2 public static void main(String[] args) {3 System.out.println("=== Setters with Validation ===\n");4 5 double initialPrice→ 1299.0 = 1299.00;6 double newPrice→ 899.99 = 899.99;7 int newStock→ 5 = 5;8 Product product = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());output=== Setters with Validation ===Product(String name, double price, int stock)
40Product(String nameLaptop, double price1299.0, int stock10) {41 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price);this.name ← Laptop
pass 1 of 241 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price1299.0);44 setStock(stock);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String nameLaptop) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name→ Laptop = nameLaptop;59}this.price ← 1299.0
pass 1 of 342 setName(name);43 setPrice(price1299.0);44 setStock(stock10);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59}6061public double getPrice() {62 return price;63}6465// Setter with validation66public void setPrice(double price1299.0) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price→ 1299.0 = price1299.0;72}All 3 passes — pass 1 is the card above pass pricestocknewPricethis.price1 1299.0 10 — 1299.0 2 899.99 — 899.99 899.99 3 -100.0 — — — this.stock ← 10, product ← ⟨Product A⟩
pass 1 of 37 int newStock = 5;8 Product product→ ⟨Product A⟩ = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());10 11 // Valid updates12 product.setPrice(newPrice);13 System.out.println("Price updated: " + product.describe());14 15 product.setStock(newStock);16 System.out.println("Stock updated: " + product.describe());17 18 // Invalid updates - rejected!19 System.out.println("\n=== Invalid Attempts ===");20 21 product.setPrice(-100); // Rejected22 System.out.println("After negative price: " + product.describe());23 24 product.setStock(-5); // Rejected 25 System.out.println("After negative stock: " + product.describe());26 27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32 }33}3435class Product {36 private String name;37 private double price;38 private int stock;39 40 Product(String name, double price, int stock) {41 // Use setters for validation even in constructor!42 setName(name);43 setPrice(price);44 setStock(stock10);45 }46 47 // Getter for name48 public String getName() {49 return name;50 }51 52 // Setter with validation53 public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59 }60 61 public double getPrice() {62 return price;63 }64 65 // Setter with validation66 public void setPrice(double price) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price = price;72 }73 74 public int getStock() {75 return stock;76 }77 78 // Setter with validation79 public void setStock(int stock10) {80 if (stock < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }84 this.stock→ 10 = stock10;85 }All 3 passes — pass 1 is the card above pass stocknewStockthis.stockproduct1 10 — 10 ⟨Product A⟩ 2 5 5 5 — 3 -5 — — — String describe()
pass 1 of 687String describe() {88 return nameLaptop + " - $" + price1299.0 + " (" + stock10 + " in stock)";89}All 6 passes — pass 1 is the card above pass pricestock1 1299.0 10 2 899.99 10 3 899.99 5 4 899.99 5 5 899.99 5 6 899.99 5 product.setPrice(newPrice);
8Product product = new Product("Laptop", initialPrice, 10);9System.out.println("Initial: " + product.describe());1011// Valid updates12product.setPrice(newPrice899.99);13System.out.println("Price updated: " + product.describe());outputInitial: Laptop - $1299.0 (10 in stock)product.setStock(newStock);
12product.setPrice(newPrice);13System.out.println("Price updated: " + product.describe());1415product.setStock(newStock5);16System.out.println("Stock updated: " + product.describe());outputPrice updated: Laptop - $899.99 (10 in stock)System.out.println("Stock updated: " + product.describe());
15product.setStock(newStock);16System.out.println("Stock updated: " + product.describe());1718// Invalid updates - rejected!19System.out.println("\n=== Invalid Attempts ===");2021product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());outputStock updated: Laptop - $899.99 (5 in stock) === Invalid Attempts ===if (price < 0)
66public void setPrice(double price) {67 if (price-100.0 < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }output [Rejected: price cannot be negative]product.setPrice(-100); // Rejected
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());System.out.println("After negative price: " + product.describe());
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());2324product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());outputAfter negative price: Laptop - $899.99 (5 in stock)if (stock < 0)
79public void setStock(int stock) {80 if (stock-5 < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }output [Rejected: stock cannot be negative]product.setStock(-5); // Rejected
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());System.out.println("After negative stock: " + product.describe());
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());2627product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());outputAfter negative stock: Laptop - $899.99 (5 in stock)public void setName(String name)
pass 2 of 252// Setter with validation53public void setName(String name(empty)) {54 if (name == null || name.isBlank()) {if (name == null || name.isBlank())
53public void setName(String name) {54 if (name(empty) == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }output [Rejected: name cannot be blank]product.setName(""); // Rejected
27product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());System.out.println("After empty name: " + product.describe());
27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32}outputAfter empty name: Laptop - $899.99 (5 in stock) === Values Unchanged === Invalid values were rejected!
initialPrice ← 999.99, newPrice ← 749.99, newStock ← 5
1public class SettersValidation {2 public static void main(String[] args) {3 System.out.println("=== Setters with Validation ===\n");4 5 double initialPrice→ 999.99 = 999.99;6 double newPrice→ 749.99 = 749.99;7 int newStock→ 5 = 5;8 Product product = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());output=== Setters with Validation ===Product(String name, double price, int stock)
40Product(String nameLaptop, double price999.99, int stock10) {41 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price);this.name ← Laptop
pass 1 of 241 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price999.99);44 setStock(stock);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String nameLaptop) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name→ Laptop = nameLaptop;59}this.price ← 999.99
pass 1 of 342 setName(name);43 setPrice(price999.99);44 setStock(stock10);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59}6061public double getPrice() {62 return price;63}6465// Setter with validation66public void setPrice(double price999.99) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price→ 999.99 = price999.99;72}All 3 passes — pass 1 is the card above pass pricestocknewPricethis.price1 999.99 10 — 999.99 2 749.99 — 749.99 749.99 3 -100.0 — — — this.stock ← 10, product ← ⟨Product A⟩
pass 1 of 37 int newStock = 5;8 Product product→ ⟨Product A⟩ = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());10 11 // Valid updates12 product.setPrice(newPrice);13 System.out.println("Price updated: " + product.describe());14 15 product.setStock(newStock);16 System.out.println("Stock updated: " + product.describe());17 18 // Invalid updates - rejected!19 System.out.println("\n=== Invalid Attempts ===");20 21 product.setPrice(-100); // Rejected22 System.out.println("After negative price: " + product.describe());23 24 product.setStock(-5); // Rejected 25 System.out.println("After negative stock: " + product.describe());26 27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32 }33}3435class Product {36 private String name;37 private double price;38 private int stock;39 40 Product(String name, double price, int stock) {41 // Use setters for validation even in constructor!42 setName(name);43 setPrice(price);44 setStock(stock10);45 }46 47 // Getter for name48 public String getName() {49 return name;50 }51 52 // Setter with validation53 public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59 }60 61 public double getPrice() {62 return price;63 }64 65 // Setter with validation66 public void setPrice(double price) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price = price;72 }73 74 public int getStock() {75 return stock;76 }77 78 // Setter with validation79 public void setStock(int stock10) {80 if (stock < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }84 this.stock→ 10 = stock10;85 }All 3 passes — pass 1 is the card above pass stocknewStockthis.stockproduct1 10 — 10 ⟨Product A⟩ 2 5 5 5 — 3 -5 — — — String describe()
pass 1 of 687String describe() {88 return nameLaptop + " - $" + price999.99 + " (" + stock10 + " in stock)";89}All 6 passes — pass 1 is the card above pass pricestock1 999.99 10 2 749.99 10 3 749.99 5 4 749.99 5 5 749.99 5 6 749.99 5 product.setPrice(newPrice);
8Product product = new Product("Laptop", initialPrice, 10);9System.out.println("Initial: " + product.describe());1011// Valid updates12product.setPrice(newPrice749.99);13System.out.println("Price updated: " + product.describe());outputInitial: Laptop - $999.99 (10 in stock)product.setStock(newStock);
12product.setPrice(newPrice);13System.out.println("Price updated: " + product.describe());1415product.setStock(newStock5);16System.out.println("Stock updated: " + product.describe());outputPrice updated: Laptop - $749.99 (10 in stock)System.out.println("Stock updated: " + product.describe());
15product.setStock(newStock);16System.out.println("Stock updated: " + product.describe());1718// Invalid updates - rejected!19System.out.println("\n=== Invalid Attempts ===");2021product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());outputStock updated: Laptop - $749.99 (5 in stock) === Invalid Attempts ===if (price < 0)
66public void setPrice(double price) {67 if (price-100.0 < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }output [Rejected: price cannot be negative]product.setPrice(-100); // Rejected
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());System.out.println("After negative price: " + product.describe());
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());2324product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());outputAfter negative price: Laptop - $749.99 (5 in stock)if (stock < 0)
79public void setStock(int stock) {80 if (stock-5 < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }output [Rejected: stock cannot be negative]product.setStock(-5); // Rejected
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());System.out.println("After negative stock: " + product.describe());
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());2627product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());outputAfter negative stock: Laptop - $749.99 (5 in stock)public void setName(String name)
pass 2 of 252// Setter with validation53public void setName(String name(empty)) {54 if (name == null || name.isBlank()) {if (name == null || name.isBlank())
53public void setName(String name) {54 if (name(empty) == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }output [Rejected: name cannot be blank]product.setName(""); // Rejected
27product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());System.out.println("After empty name: " + product.describe());
27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32}outputAfter empty name: Laptop - $749.99 (5 in stock) === Values Unchanged === Invalid values were rejected!
initialPrice ← 999.99, newPrice ← 1099.99, newStock ← 5
1public class SettersValidation {2 public static void main(String[] args) {3 System.out.println("=== Setters with Validation ===\n");4 5 double initialPrice→ 999.99 = 999.99;6 double newPrice→ 1099.99 = 1099.99;7 int newStock→ 5 = 5;8 Product product = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());output=== Setters with Validation ===Product(String name, double price, int stock)
40Product(String nameLaptop, double price999.99, int stock10) {41 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price);this.name ← Laptop
pass 1 of 241 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price999.99);44 setStock(stock);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String nameLaptop) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name→ Laptop = nameLaptop;59}this.price ← 999.99
pass 1 of 342 setName(name);43 setPrice(price999.99);44 setStock(stock10);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59}6061public double getPrice() {62 return price;63}6465// Setter with validation66public void setPrice(double price999.99) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price→ 999.99 = price999.99;72}All 3 passes — pass 1 is the card above pass pricestocknewPricethis.price1 999.99 10 — 999.99 2 1099.99 — 1099.99 1099.99 3 -100.0 — — — this.stock ← 10, product ← ⟨Product A⟩
pass 1 of 37 int newStock = 5;8 Product product→ ⟨Product A⟩ = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());10 11 // Valid updates12 product.setPrice(newPrice);13 System.out.println("Price updated: " + product.describe());14 15 product.setStock(newStock);16 System.out.println("Stock updated: " + product.describe());17 18 // Invalid updates - rejected!19 System.out.println("\n=== Invalid Attempts ===");20 21 product.setPrice(-100); // Rejected22 System.out.println("After negative price: " + product.describe());23 24 product.setStock(-5); // Rejected 25 System.out.println("After negative stock: " + product.describe());26 27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32 }33}3435class Product {36 private String name;37 private double price;38 private int stock;39 40 Product(String name, double price, int stock) {41 // Use setters for validation even in constructor!42 setName(name);43 setPrice(price);44 setStock(stock10);45 }46 47 // Getter for name48 public String getName() {49 return name;50 }51 52 // Setter with validation53 public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59 }60 61 public double getPrice() {62 return price;63 }64 65 // Setter with validation66 public void setPrice(double price) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price = price;72 }73 74 public int getStock() {75 return stock;76 }77 78 // Setter with validation79 public void setStock(int stock10) {80 if (stock < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }84 this.stock→ 10 = stock10;85 }All 3 passes — pass 1 is the card above pass stocknewStockthis.stockproduct1 10 — 10 ⟨Product A⟩ 2 5 5 5 — 3 -5 — — — String describe()
pass 1 of 687String describe() {88 return nameLaptop + " - $" + price999.99 + " (" + stock10 + " in stock)";89}All 6 passes — pass 1 is the card above pass pricestock1 999.99 10 2 1099.99 10 3 1099.99 5 4 1099.99 5 5 1099.99 5 6 1099.99 5 product.setPrice(newPrice);
8Product product = new Product("Laptop", initialPrice, 10);9System.out.println("Initial: " + product.describe());1011// Valid updates12product.setPrice(newPrice1099.99);13System.out.println("Price updated: " + product.describe());outputInitial: Laptop - $999.99 (10 in stock)product.setStock(newStock);
12product.setPrice(newPrice);13System.out.println("Price updated: " + product.describe());1415product.setStock(newStock5);16System.out.println("Stock updated: " + product.describe());outputPrice updated: Laptop - $1099.99 (10 in stock)System.out.println("Stock updated: " + product.describe());
15product.setStock(newStock);16System.out.println("Stock updated: " + product.describe());1718// Invalid updates - rejected!19System.out.println("\n=== Invalid Attempts ===");2021product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());outputStock updated: Laptop - $1099.99 (5 in stock) === Invalid Attempts ===if (price < 0)
66public void setPrice(double price) {67 if (price-100.0 < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }output [Rejected: price cannot be negative]product.setPrice(-100); // Rejected
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());System.out.println("After negative price: " + product.describe());
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());2324product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());outputAfter negative price: Laptop - $1099.99 (5 in stock)if (stock < 0)
79public void setStock(int stock) {80 if (stock-5 < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }output [Rejected: stock cannot be negative]product.setStock(-5); // Rejected
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());System.out.println("After negative stock: " + product.describe());
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());2627product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());outputAfter negative stock: Laptop - $1099.99 (5 in stock)public void setName(String name)
pass 2 of 252// Setter with validation53public void setName(String name(empty)) {54 if (name == null || name.isBlank()) {if (name == null || name.isBlank())
53public void setName(String name) {54 if (name(empty) == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }output [Rejected: name cannot be blank]product.setName(""); // Rejected
27product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());System.out.println("After empty name: " + product.describe());
27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32}outputAfter empty name: Laptop - $1099.99 (5 in stock) === Values Unchanged === Invalid values were rejected!
initialPrice ← 999.99, newPrice ← 899.99, newStock ← 0
1public class SettersValidation {2 public static void main(String[] args) {3 System.out.println("=== Setters with Validation ===\n");4 5 double initialPrice→ 999.99 = 999.99;6 double newPrice→ 899.99 = 899.99;7 int newStock→ 0 = 0;8 Product product = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());output=== Setters with Validation ===Product(String name, double price, int stock)
40Product(String nameLaptop, double price999.99, int stock10) {41 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price);this.name ← Laptop
pass 1 of 241 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price999.99);44 setStock(stock);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String nameLaptop) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name→ Laptop = nameLaptop;59}this.price ← 999.99
pass 1 of 342 setName(name);43 setPrice(price999.99);44 setStock(stock10);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59}6061public double getPrice() {62 return price;63}6465// Setter with validation66public void setPrice(double price999.99) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price→ 999.99 = price999.99;72}All 3 passes — pass 1 is the card above pass pricestocknewPricethis.price1 999.99 10 — 999.99 2 899.99 — 899.99 899.99 3 -100.0 — — — this.stock ← 10, product ← ⟨Product A⟩
pass 1 of 37 int newStock = 0;8 Product product→ ⟨Product A⟩ = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());10 11 // Valid updates12 product.setPrice(newPrice);13 System.out.println("Price updated: " + product.describe());14 15 product.setStock(newStock);16 System.out.println("Stock updated: " + product.describe());17 18 // Invalid updates - rejected!19 System.out.println("\n=== Invalid Attempts ===");20 21 product.setPrice(-100); // Rejected22 System.out.println("After negative price: " + product.describe());23 24 product.setStock(-5); // Rejected 25 System.out.println("After negative stock: " + product.describe());26 27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32 }33}3435class Product {36 private String name;37 private double price;38 private int stock;39 40 Product(String name, double price, int stock) {41 // Use setters for validation even in constructor!42 setName(name);43 setPrice(price);44 setStock(stock10);45 }46 47 // Getter for name48 public String getName() {49 return name;50 }51 52 // Setter with validation53 public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59 }60 61 public double getPrice() {62 return price;63 }64 65 // Setter with validation66 public void setPrice(double price) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price = price;72 }73 74 public int getStock() {75 return stock;76 }77 78 // Setter with validation79 public void setStock(int stock10) {80 if (stock < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }84 this.stock→ 10 = stock10;85 }All 3 passes — pass 1 is the card above pass stocknewStockthis.stockproduct1 10 — 10 ⟨Product A⟩ 2 0 0 0 — 3 -5 — — — String describe()
pass 1 of 687String describe() {88 return nameLaptop + " - $" + price999.99 + " (" + stock10 + " in stock)";89}All 6 passes — pass 1 is the card above pass pricestock1 999.99 10 2 899.99 10 3 899.99 0 4 899.99 0 5 899.99 0 6 899.99 0 product.setPrice(newPrice);
8Product product = new Product("Laptop", initialPrice, 10);9System.out.println("Initial: " + product.describe());1011// Valid updates12product.setPrice(newPrice899.99);13System.out.println("Price updated: " + product.describe());outputInitial: Laptop - $999.99 (10 in stock)product.setStock(newStock);
12product.setPrice(newPrice);13System.out.println("Price updated: " + product.describe());1415product.setStock(newStock0);16System.out.println("Stock updated: " + product.describe());outputPrice updated: Laptop - $899.99 (10 in stock)System.out.println("Stock updated: " + product.describe());
15product.setStock(newStock);16System.out.println("Stock updated: " + product.describe());1718// Invalid updates - rejected!19System.out.println("\n=== Invalid Attempts ===");2021product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());outputStock updated: Laptop - $899.99 (0 in stock) === Invalid Attempts ===if (price < 0)
66public void setPrice(double price) {67 if (price-100.0 < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }output [Rejected: price cannot be negative]product.setPrice(-100); // Rejected
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());System.out.println("After negative price: " + product.describe());
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());2324product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());outputAfter negative price: Laptop - $899.99 (0 in stock)if (stock < 0)
79public void setStock(int stock) {80 if (stock-5 < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }output [Rejected: stock cannot be negative]product.setStock(-5); // Rejected
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());System.out.println("After negative stock: " + product.describe());
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());2627product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());outputAfter negative stock: Laptop - $899.99 (0 in stock)public void setName(String name)
pass 2 of 252// Setter with validation53public void setName(String name(empty)) {54 if (name == null || name.isBlank()) {if (name == null || name.isBlank())
53public void setName(String name) {54 if (name(empty) == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }output [Rejected: name cannot be blank]product.setName(""); // Rejected
27product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());System.out.println("After empty name: " + product.describe());
27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32}outputAfter empty name: Laptop - $899.99 (0 in stock) === Values Unchanged === Invalid values were rejected!
initialPrice ← 999.99, newPrice ← 899.99, newStock ← 25
1public class SettersValidation {2 public static void main(String[] args) {3 System.out.println("=== Setters with Validation ===\n");4 5 double initialPrice→ 999.99 = 999.99;6 double newPrice→ 899.99 = 899.99;7 int newStock→ 25 = 25;8 Product product = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());output=== Setters with Validation ===Product(String name, double price, int stock)
40Product(String nameLaptop, double price999.99, int stock10) {41 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price);this.name ← Laptop
pass 1 of 241 // Use setters for validation even in constructor!42 setName(nameLaptop);43 setPrice(price999.99);44 setStock(stock);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String nameLaptop) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name→ Laptop = nameLaptop;59}this.price ← 999.99
pass 1 of 342 setName(name);43 setPrice(price999.99);44 setStock(stock10);45}4647// Getter for name48public String getName() {49 return name;50}5152// Setter with validation53public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59}6061public double getPrice() {62 return price;63}6465// Setter with validation66public void setPrice(double price999.99) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price→ 999.99 = price999.99;72}All 3 passes — pass 1 is the card above pass pricestocknewPricethis.price1 999.99 10 — 999.99 2 899.99 — 899.99 899.99 3 -100.0 — — — this.stock ← 10, product ← ⟨Product A⟩
pass 1 of 37 int newStock = 25;8 Product product→ ⟨Product A⟩ = new Product("Laptop", initialPrice, 10);9 System.out.println("Initial: " + product.describe());10 11 // Valid updates12 product.setPrice(newPrice);13 System.out.println("Price updated: " + product.describe());14 15 product.setStock(newStock);16 System.out.println("Stock updated: " + product.describe());17 18 // Invalid updates - rejected!19 System.out.println("\n=== Invalid Attempts ===");20 21 product.setPrice(-100); // Rejected22 System.out.println("After negative price: " + product.describe());23 24 product.setStock(-5); // Rejected 25 System.out.println("After negative stock: " + product.describe());26 27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32 }33}3435class Product {36 private String name;37 private double price;38 private int stock;39 40 Product(String name, double price, int stock) {41 // Use setters for validation even in constructor!42 setName(name);43 setPrice(price);44 setStock(stock10);45 }46 47 // Getter for name48 public String getName() {49 return name;50 }51 52 // Setter with validation53 public void setName(String name) {54 if (name == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }58 this.name = name;59 }60 61 public double getPrice() {62 return price;63 }64 65 // Setter with validation66 public void setPrice(double price) {67 if (price < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }71 this.price = price;72 }73 74 public int getStock() {75 return stock;76 }77 78 // Setter with validation79 public void setStock(int stock10) {80 if (stock < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }84 this.stock→ 10 = stock10;85 }All 3 passes — pass 1 is the card above pass stocknewStockthis.stockproduct1 10 — 10 ⟨Product A⟩ 2 25 25 25 — 3 -5 — — — String describe()
pass 1 of 687String describe() {88 return nameLaptop + " - $" + price999.99 + " (" + stock10 + " in stock)";89}All 6 passes — pass 1 is the card above pass pricestock1 999.99 10 2 899.99 10 3 899.99 25 4 899.99 25 5 899.99 25 6 899.99 25 product.setPrice(newPrice);
8Product product = new Product("Laptop", initialPrice, 10);9System.out.println("Initial: " + product.describe());1011// Valid updates12product.setPrice(newPrice899.99);13System.out.println("Price updated: " + product.describe());outputInitial: Laptop - $999.99 (10 in stock)product.setStock(newStock);
12product.setPrice(newPrice);13System.out.println("Price updated: " + product.describe());1415product.setStock(newStock25);16System.out.println("Stock updated: " + product.describe());outputPrice updated: Laptop - $899.99 (10 in stock)System.out.println("Stock updated: " + product.describe());
15product.setStock(newStock);16System.out.println("Stock updated: " + product.describe());1718// Invalid updates - rejected!19System.out.println("\n=== Invalid Attempts ===");2021product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());outputStock updated: Laptop - $899.99 (25 in stock) === Invalid Attempts ===if (price < 0)
66public void setPrice(double price) {67 if (price-100.0 < 0) {68 System.out.println(" [Rejected: price cannot be negative]");69 return;70 }output [Rejected: price cannot be negative]product.setPrice(-100); // Rejected
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());System.out.println("After negative price: " + product.describe());
21product.setPrice(-100); // Rejected22System.out.println("After negative price: " + product.describe());2324product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());outputAfter negative price: Laptop - $899.99 (25 in stock)if (stock < 0)
79public void setStock(int stock) {80 if (stock-5 < 0) {81 System.out.println(" [Rejected: stock cannot be negative]");82 return;83 }output [Rejected: stock cannot be negative]product.setStock(-5); // Rejected
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());System.out.println("After negative stock: " + product.describe());
24product.setStock(-5); // Rejected 25System.out.println("After negative stock: " + product.describe());2627product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());outputAfter negative stock: Laptop - $899.99 (25 in stock)public void setName(String name)
pass 2 of 252// Setter with validation53public void setName(String name(empty)) {54 if (name == null || name.isBlank()) {if (name == null || name.isBlank())
53public void setName(String name) {54 if (name(empty) == null || name.isBlank()) {55 System.out.println(" [Rejected: name cannot be blank]");56 return;57 }output [Rejected: name cannot be blank]product.setName(""); // Rejected
27product.setName(""); // Rejected28System.out.println("After empty name: " + product.describe());System.out.println("After empty name: " + product.describe());
27 product.setName(""); // Rejected28 System.out.println("After empty name: " + product.describe());29 30 System.out.println("\n=== Values Unchanged ===");31 System.out.println("Invalid values were rejected!");32}outputAfter empty name: Laptop - $899.99 (25 in stock) === Values Unchanged === Invalid values were rejected!
Setters can validate before assigning. Reject invalid values.
Read-only properties
Some fields should never be changed after creation.
public class Readonly {
public static void main(String[] args) {
System.out.println("=== Read-Only Properties ===\n");
// Create a circle
Circle circle = new Circle(5.0);
// Can read all properties
System.out.println("Radius: " + circle.getRadius());
System.out.println("Area: " + circle.getArea());
System.out.println("Circumference: " + circle.getCircumference());
// Cannot change radius - no setter!
// circle.setRadius(10); // No such method!
// circle.radius = 10; // Private field!
System.out.println("\n=== Order Example ===");
Order order = new Order("ORD-12345", 99.99);
System.out.println("Order ID: " + order.getId());
System.out.println("Total: $" + order.getTotal());
System.out.println("Created: " + order.getCreatedTime());
// ID and creation time are read-only
// order.setId("ORD-99999"); // No such method
// order.setCreatedTime(...); // No such method
// But total can be updated
order.setTotal(149.99);
System.out.println("Updated total: $" + order.getTotal());
}
}
class Circle {
private final double radius;
Circle(double radius) {
this.radius = radius;
}
// Only getter, no setter
public double getRadius() {
return radius;
}
// Computed properties are naturally read-only
public double getArea() {
return Math.PI * radius * radius;
}
public double getCircumference() {
return 2 * Math.PI * radius;
}
}
class Order {
private final String id;
private final long createdTime;
private double total; // This one can change
Order(String id, double total) {
this.id = id;
this.createdTime = 1736937000000L;
this.total = total;
}
// Read-only: no setters
public String getId() {
return id;
}
public long getCreatedTime() {
return createdTime;
}
// Read-write: has getter AND setter
public double getTotal() {
return total;
}
public void setTotal(double total) {
if (total >= 0) {
this.total = total;
}
}
}
public static void main(String[] args)
1public class Readonly {2 public static void main(String[] args) {3 System.out.println("=== Read-Only Properties ===\n");4 5 // Create a circle //?create6 Circle circle = new Circle(5.0);output=== Read-Only Properties ===this.radius ← 5.0, circle ← ⟨Circle A⟩
5 // Create a circle //?create6 Circle circle→ ⟨Circle A⟩ = new Circle(5.0);7 8 // Can read all properties //?read9 System.out.println("Radius: " + circle.getRadius());10 System.out.println("Area: " + circle.getArea());11 System.out.println("Circumference: " + circle.getCircumference());12 13 // Cannot change radius - no setter! //?noset14 // circle.setRadius(10); // No such method!15 // circle.radius = 10; // Private field!16 17 System.out.println("\n=== Order Example ===");18 19 Order order = new Order("ORD-12345", 99.99); //?order20 21 System.out.println("Order ID: " + order.getId());22 System.out.println("Total: $" + order.getTotal());23 System.out.println("Created: " + order.getCreatedTime());24 25 // ID and creation time are read-only //?orderreadonly26 // order.setId("ORD-99999"); // No such method27 // order.setCreatedTime(...); // No such method28 29 // But total can be updated30 order.setTotal(149.99);31 System.out.println("Updated total: $" + order.getTotal());32 }33}3435class Circle {36 private final double radius; //?final37 38 Circle(double radius5.0) {39 this.radius→ 5.0 = radius5.0;40 }public double getRadius()
42// Only getter, no setter //?getteronly43public double getRadius() {44 return radius5.0;45}System.out.println("Radius: " + circle.getRadius());
8// Can read all properties //?read9System.out.println("Radius: " + circle.getRadius());10System.out.println("Area: " + circle.getArea());11System.out.println("Circumference: " + circle.getCircumference());outputRadius: 5.0public double getArea()
47// Computed properties are naturally read-only //?computed48public double getArea() {49 return Math.PI * radius5.0 * radius;50}System.out.println("Area: " + circle.getArea());
9System.out.println("Radius: " + circle.getRadius());10System.out.println("Area: " + circle.getArea());11System.out.println("Circumference: " + circle.getCircumference());outputArea: 78.53981633974483public double getCircumference()
52public double getCircumference() {53 return 2 * Math.PI * radius5.0;54}System.out.println("Circumference: " + circle.getCircumference());
10System.out.println("Area: " + circle.getArea());11System.out.println("Circumference: " + circle.getCircumference());1213// Cannot change radius - no setter! //?noset14// circle.setRadius(10); // No such method!15// circle.radius = 10; // Private field!1617System.out.println("\n=== Order Example ===");1819Order order = new Order("ORD-12345", 99.99); //?orderoutputCircumference: 31.41592653589793 === Order Example ===this.id ← ORD-12345, this.createdTime ← 1736937000000, this.total ← 99.99
19 Order order→ ⟨Order B⟩ = new Order("ORD-12345", 99.99); //?order20 21 System.out.println("Order ID: " + order.getId());22 System.out.println("Total: $" + order.getTotal());23 System.out.println("Created: " + order.getCreatedTime());24 25 // ID and creation time are read-only //?orderreadonly26 // order.setId("ORD-99999"); // No such method27 // order.setCreatedTime(...); // No such method28 29 // But total can be updated30 order.setTotal(149.99);31 System.out.println("Updated total: $" + order.getTotal());32 }33}3435class Circle {36 private final double radius; //?final37 38 Circle(double radius) {39 this.radius = radius;40 }41 42 // Only getter, no setter //?getteronly43 public double getRadius() {44 return radius;45 }46 47 // Computed properties are naturally read-only //?computed48 public double getArea() {49 return Math.PI * radius * radius;50 }51 52 public double getCircumference() {53 return 2 * Math.PI * radius;54 }55}5657class Order {58 private final String id; //?orderfields59 private final long createdTime;60 private double total; // This one can change61 62 Order(String idORD-12345, double total99.99) {63 this.id→ ORD-12345 = idORD-12345;64 this.createdTime→ 1736937000000 = 1736937000000L;65 this.total→ 99.99 = total99.99;66 }public String getId()
68// Read-only: no setters69public String getId() {70 return idORD-12345;71}System.out.println("Order ID: " + order.getId());
21System.out.println("Order ID: " + order.getId());22System.out.println("Total: $" + order.getTotal());23System.out.println("Created: " + order.getCreatedTime());outputOrder ID: ORD-12345public double getTotal()
pass 1 of 277// Read-write: has getter AND setter78public double getTotal() {79 return total99.99;80}System.out.println("Total: $" + order.getTotal());
21System.out.println("Order ID: " + order.getId());22System.out.println("Total: $" + order.getTotal());23System.out.println("Created: " + order.getCreatedTime());outputTotal: $99.99public long getCreatedTime()
73public long getCreatedTime() {74 return createdTime1736937000000;75}System.out.println("Created: " + order.getCreatedTime());
22System.out.println("Total: $" + order.getTotal());23System.out.println("Created: " + order.getCreatedTime());2425// ID and creation time are read-only //?orderreadonly26// order.setId("ORD-99999"); // No such method27// order.setCreatedTime(...); // No such method2829// But total can be updated30order.setTotal(149.99);31System.out.println("Updated total: $" + order.getTotal());outputCreated: 1736937000000public void setTotal(double total)
82public void setTotal(double total149.99) { //?settotal83 if (total >= 0) {this.total ← 149.99
29 // But total can be updated30 order.setTotal(149.99);31 System.out.println("Updated total: $" + order.getTotal());32 }33}3435class Circle {36 private final double radius; //?final37 38 Circle(double radius) {39 this.radius = radius;40 }41 42 // Only getter, no setter //?getteronly43 public double getRadius() {44 return radius;45 }46 47 // Computed properties are naturally read-only //?computed48 public double getArea() {49 return Math.PI * radius * radius;50 }51 52 public double getCircumference() {53 return 2 * Math.PI * radius;54 }55}5657class Order {58 private final String id; //?orderfields59 private final long createdTime;60 private double total; // This one can change61 62 Order(String id, double total) {63 this.id = id;64 this.createdTime = 1736937000000L;65 this.total = total;66 }67 68 // Read-only: no setters69 public String getId() {70 return id;71 }72 73 public long getCreatedTime() {74 return createdTime;75 }76 77 // Read-write: has getter AND setter78 public double getTotal() {79 return total;80 }81 82 public void setTotal(double total) { //?settotal83 if (total149.99 >= 0) {84 this.total→ 149.99 = total149.99;85 }public double getTotal()
pass 2 of 277// Read-write: has getter AND setter78public double getTotal() {79 return total149.99;80}System.out.println("Updated total: $" + order.getTotal());
30 order.setTotal(149.99);31 System.out.println("Updated total: $" + order.getTotal());32}outputUpdated total: $149.99
Provide getter but no setter. Field set only in constructor.
Computed properties
Return calculated values, not stored fields.
public class ComputedProperties {
public static void main(String[] args) {
System.out.println("=== Computed Properties ===\n");
Rectangle rect = new Rectangle(5, 3);
// Stored properties
System.out.println("Width: " + rect.getWidth());
System.out.println("Height: " + rect.getHeight());
// Computed properties
System.out.println("Area: " + rect.getArea());
System.out.println("Perimeter: " + rect.getPerimeter());
System.out.println("Is square: " + rect.isSquare());
// Change dimensions
System.out.println("\n--- After resize ---");
rect.setWidth(4);
rect.setHeight(4);
System.out.println("Width: " + rect.getWidth());
System.out.println("Height: " + rect.getHeight());
System.out.println("Area: " + rect.getArea());
System.out.println("Is square: " + rect.isSquare());
System.out.println("\n=== Temperature Example ===");
Temperature temp = new Temperature(100, "C");
System.out.println("Celsius: " + temp.getCelsius());
System.out.println("Fahrenheit: " + temp.getFahrenheit());
System.out.println("Kelvin: " + temp.getKelvin());
}
}
class Rectangle {
private double width;
private double height;
// Note: no area or perimeter fields!
Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getWidth() { return width; }
public double getHeight() { return height; }
public void setWidth(double width) {
if (width > 0) this.width = width;
}
public void setHeight(double height) {
if (height > 0) this.height = height;
}
// Computed: calculated from width and height
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public boolean isSquare() {
return width == height;
}
}
class Temperature {
private double celsius;
// Store only one value, compute others
Temperature(double value, String unit) {
switch (unit.toUpperCase()) {
case "C" -> this.celsius = value;
case "F" -> this.celsius = (value - 32) * 5 / 9;
case "K" -> this.celsius = value - 273.15;
default -> this.celsius = value;
}
}
// All three are getters, only one is stored
public double getCelsius() {
return celsius;
}
public double getFahrenheit() {
return celsius * 9 / 5 + 32;
}
public double getKelvin() {
return celsius + 273.15;
}
}
public static void main(String[] args)
1public class ComputedProperties {2 public static void main(String[] args) {3 System.out.println("=== Computed Properties ===\n");4 5 Rectangle rect = new Rectangle(5, 3); //?createoutput=== Computed Properties ===this.width ← 5.0, this.height ← 3.0, rect ← ⟨Rectangle A⟩
5 Rectangle rect→ ⟨Rectangle A⟩ = new Rectangle(5, 3); //?create6 7 // Stored properties //?stored8 System.out.println("Width: " + rect.getWidth());9 System.out.println("Height: " + rect.getHeight());10 11 // Computed properties //?computed12 System.out.println("Area: " + rect.getArea());13 System.out.println("Perimeter: " + rect.getPerimeter());14 System.out.println("Is square: " + rect.isSquare());15 16 // Change dimensions //?change17 System.out.println("\n--- After resize ---");18 rect.setWidth(4);19 rect.setHeight(4);20 21 System.out.println("Width: " + rect.getWidth());22 System.out.println("Height: " + rect.getHeight());23 System.out.println("Area: " + rect.getArea());24 System.out.println("Is square: " + rect.isSquare());25 26 System.out.println("\n=== Temperature Example ===");27 Temperature temp = new Temperature(100, "C"); //?temp28 System.out.println("Celsius: " + temp.getCelsius());29 System.out.println("Fahrenheit: " + temp.getFahrenheit());30 System.out.println("Kelvin: " + temp.getKelvin());31 }32}3334class Rectangle {35 private double width; //?rectfields36 private double height;37 // Note: no area or perimeter fields!38 39 Rectangle(double width5.0, double height3.0) {40 this.width→ 5.0 = width5.0;41 this.height→ 3.0 = height3.0;42 }public double getWidth()
pass 1 of 244public double getWidth() { return width5.0; }45public double getHeight() { return height; }System.out.println("Width: " + rect.getWidth());
7// Stored properties //?stored8System.out.println("Width: " + rect.getWidth());9System.out.println("Height: " + rect.getHeight());outputWidth: 5.0public double getHeight()
pass 1 of 244public double getWidth() { return width; }45public double getHeight() { return height3.0; }System.out.println("Height: " + rect.getHeight());
8System.out.println("Width: " + rect.getWidth());9System.out.println("Height: " + rect.getHeight());1011// Computed properties //?computed12System.out.println("Area: " + rect.getArea());13System.out.println("Perimeter: " + rect.getPerimeter());outputHeight: 3.0public double getArea()
pass 1 of 255// Computed: calculated from width and height //?rectcomputed56public double getArea() {57 return width5.0 * height3.0;58}System.out.println("Area: " + rect.getArea());
11// Computed properties //?computed12System.out.println("Area: " + rect.getArea());13System.out.println("Perimeter: " + rect.getPerimeter());14System.out.println("Is square: " + rect.isSquare());outputArea: 15.0public double getPerimeter()
60public double getPerimeter() {61 return 2 * (width5.0 + height3.0);62}System.out.println("Perimeter: " + rect.getPerimeter());
12System.out.println("Area: " + rect.getArea());13System.out.println("Perimeter: " + rect.getPerimeter());14System.out.println("Is square: " + rect.isSquare());outputPerimeter: 16.0public boolean isSquare()
pass 1 of 264public boolean isSquare() {65 return width5.0 == height3.0;66}System.out.println("Is square: " + rect.isSquare());
13System.out.println("Perimeter: " + rect.getPerimeter());14System.out.println("Is square: " + rect.isSquare());1516// Change dimensions //?change17System.out.println("\n--- After resize ---");18rect.setWidth(4);19rect.setHeight(4);outputIs square: false --- After resize ---public void setWidth(double width)
47public void setWidth(double width4.0) { //?setwidth48 if (width > 0) this.width = width;this.width ← 4.0
17 System.out.println("\n--- After resize ---");18 rect.setWidth(4);19 rect.setHeight(4);20 21 System.out.println("Width: " + rect.getWidth());22 System.out.println("Height: " + rect.getHeight());23 System.out.println("Area: " + rect.getArea());24 System.out.println("Is square: " + rect.isSquare());25 26 System.out.println("\n=== Temperature Example ===");27 Temperature temp = new Temperature(100, "C"); //?temp28 System.out.println("Celsius: " + temp.getCelsius());29 System.out.println("Fahrenheit: " + temp.getFahrenheit());30 System.out.println("Kelvin: " + temp.getKelvin());31 }32}3334class Rectangle {35 private double width; //?rectfields36 private double height;37 // Note: no area or perimeter fields!38 39 Rectangle(double width, double height) {40 this.width = width;41 this.height = height;42 }43 44 public double getWidth() { return width; }45 public double getHeight() { return height; }46 47 public void setWidth(double width) { //?setwidth48 if (width4.0 > 0) this.width→ 4.0 = width;49 }public void setHeight(double height)
51public void setHeight(double height4.0) {52 if (height > 0) this.height = height;this.height ← 4.0
18 rect.setWidth(4);19 rect.setHeight(4);20 21 System.out.println("Width: " + rect.getWidth());22 System.out.println("Height: " + rect.getHeight());23 System.out.println("Area: " + rect.getArea());24 System.out.println("Is square: " + rect.isSquare());25 26 System.out.println("\n=== Temperature Example ===");27 Temperature temp = new Temperature(100, "C"); //?temp28 System.out.println("Celsius: " + temp.getCelsius());29 System.out.println("Fahrenheit: " + temp.getFahrenheit());30 System.out.println("Kelvin: " + temp.getKelvin());31 }32}3334class Rectangle {35 private double width; //?rectfields36 private double height;37 // Note: no area or perimeter fields!38 39 Rectangle(double width, double height) {40 this.width = width;41 this.height = height;42 }43 44 public double getWidth() { return width; }45 public double getHeight() { return height; }46 47 public void setWidth(double width) { //?setwidth48 if (width > 0) this.width = width;49 }50 51 public void setHeight(double height) {52 if (height4.0 > 0) this.height→ 4.0 = height;53 }public double getWidth()
pass 2 of 244public double getWidth() { return width4.0; }45public double getHeight() { return height; }System.out.println("Width: " + rect.getWidth());
21System.out.println("Width: " + rect.getWidth());22System.out.println("Height: " + rect.getHeight());23System.out.println("Area: " + rect.getArea());outputWidth: 4.0public double getHeight()
pass 2 of 244public double getWidth() { return width; }45public double getHeight() { return height4.0; }System.out.println("Height: " + rect.getHeight());
21System.out.println("Width: " + rect.getWidth());22System.out.println("Height: " + rect.getHeight());23System.out.println("Area: " + rect.getArea());24System.out.println("Is square: " + rect.isSquare());outputHeight: 4.0public double getArea()
pass 2 of 255// Computed: calculated from width and height //?rectcomputed56public double getArea() {57 return width4.0 * height4.0;58}System.out.println("Area: " + rect.getArea());
22System.out.println("Height: " + rect.getHeight());23System.out.println("Area: " + rect.getArea());24System.out.println("Is square: " + rect.isSquare());outputArea: 16.0public boolean isSquare()
pass 2 of 264public boolean isSquare() {65 return width4.0 == height4.0;66}System.out.println("Is square: " + rect.isSquare());
23System.out.println("Area: " + rect.getArea());24System.out.println("Is square: " + rect.isSquare());2526System.out.println("\n=== Temperature Example ===");27Temperature temp = new Temperature(100, "C"); //?temp28System.out.println("Celsius: " + temp.getCelsius());outputIs square: true === Temperature Example ===temp ← ⟨Temperature B⟩
26 System.out.println("\n=== Temperature Example ===");27 Temperature temp→ ⟨Temperature B⟩ = new Temperature(100, "C"); //?temp28 System.out.println("Celsius: " + temp.getCelsius());29 System.out.println("Fahrenheit: " + temp.getFahrenheit());30 System.out.println("Kelvin: " + temp.getKelvin());31 }32}3334class Rectangle {35 private double width; //?rectfields36 private double height;37 // Note: no area or perimeter fields!38 39 Rectangle(double width, double height) {40 this.width = width;41 this.height = height;42 }43 44 public double getWidth() { return width; }45 public double getHeight() { return height; }46 47 public void setWidth(double width) { //?setwidth48 if (width > 0) this.width = width;49 }50 51 public void setHeight(double height) {52 if (height > 0) this.height = height;53 }54 55 // Computed: calculated from width and height //?rectcomputed56 public double getArea() {57 return width * height;58 }59 60 public double getPerimeter() {61 return 2 * (width + height);62 }63 64 public boolean isSquare() {65 return width == height;66 }67}6869class Temperature {70 private double celsius; //?tempfield71 // Store only one value, compute others72 73 Temperature(double value100.0, String unitC) { //?tempctr74 switch (unit.toUpperCase()) {public double getCelsius()
82// All three are getters, only one is stored //?tempgetters83public double getCelsius() {84 return celsius100.0;85}System.out.println("Celsius: " + temp.getCelsius());
27Temperature temp = new Temperature(100, "C"); //?temp28System.out.println("Celsius: " + temp.getCelsius());29System.out.println("Fahrenheit: " + temp.getFahrenheit());30System.out.println("Kelvin: " + temp.getKelvin());outputCelsius: 100.0public double getFahrenheit()
87public double getFahrenheit() {88 return celsius100.0 * 9 / 5 + 32;89}System.out.println("Fahrenheit: " + temp.getFahrenheit());
28 System.out.println("Celsius: " + temp.getCelsius());29 System.out.println("Fahrenheit: " + temp.getFahrenheit());30 System.out.println("Kelvin: " + temp.getKelvin());31}outputFahrenheit: 212.0public double getKelvin()
91public double getKelvin() {92 return celsius100.0 + 273.15;93}System.out.println("Kelvin: " + temp.getKelvin());
29 System.out.println("Fahrenheit: " + temp.getFahrenheit());30 System.out.println("Kelvin: " + temp.getKelvin());31}outputKelvin: 373.15
Getters can compute values from other fields. Caller doesn't know the difference.
Exercise: ImmutableClass.java
Create a fully immutable class - no changes after construction