Skip to content

Commit 177c8b5

Browse files
committed
Added a demo of using the java.util.function.Consumer interface
1 parent 8a3c16f commit 177c8b5

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package org.bsnyder.java18.examples;
2+
3+
import java.util.function.Consumer;
4+
5+
class Customer {
6+
private String ssn;
7+
private Double balance;
8+
9+
public Customer(String ssn, Double balance) {
10+
this.ssn = ssn;
11+
this.balance = balance;
12+
}
13+
14+
public String getSsn() {
15+
return ssn;
16+
}
17+
18+
public Double getBalance() {
19+
return balance;
20+
}
21+
22+
public void setBalance(Double balance) {
23+
this.balance = balance;
24+
}
25+
26+
}
27+
28+
class Bank {
29+
30+
public void updateBalance(Customer customer, Consumer<Customer> consumer) {
31+
System.out.println(" SSN: " + customer.getSsn());
32+
System.out.println("Balance before tx: " + customer.getBalance());
33+
consumer.accept(customer);
34+
System.out.println(" Balance after tx: " + customer.getBalance());
35+
}
36+
}
37+
38+
public class ConsumerDemo {
39+
40+
public static void main(String[] args) {
41+
Bank bank = new Bank();
42+
Customer customer = new Customer("000-00-0000", 5000.0);
43+
bank.updateBalance(customer, c -> c.setBalance(c.getBalance() + 2000.0));
44+
System.out.println("-----------------------");
45+
bank.updateBalance(customer, c -> c.setBalance(c.getBalance() - 500.0));
46+
}
47+
}

0 commit comments

Comments
 (0)