-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
207 lines (195 loc) · 10.3 KB
/
Copy pathMain.java
File metadata and controls
207 lines (195 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**
* ================================================
* CLASE MAIN - CAJERO
* ================================================
*
* ¿QUÉ ES?
* --------
* Main es el PUNTO DE ENTRADA del proyecto Cajero.
* Aquí DEMOSTRAMOS cómo funciona Encapsulación y Control de acceso.
*
* ¿PARA QUÉ SIRVE?
* ----------------
* Mostrar ejemplos PRÁCTICOS de:
* 1. Cómo la encapsulación PROTEGE los datos
* 2. Por qué los GETTERS son seguros (solo lectura)
* 3. Por qué los SETTERS son peligrosos (sin control)
* 4. Por qué los MÉTODOS CONTROLADOS son la solución
*
* ¿ANALOGÍA?
* ----------
* Imaginemos un BANCO real:
* - GETTERS: Preguntar al cajero "¿cuánto tengo?" → te dice
* - SETTERS: Intentar cambiar dinero directamente → ❌ IMPOSIBLE
* - MÉTODOS CONTROLADOS: Decir "quiero sacar 100€" → valida y realiza
*
* ¿POR QUÉ ESTA DEMOSTRACIÓN?
* ----------------------------
* Es MUY FÁCIL decir:
* "Encapsulación es guardar datos en private"
* Pero es DIFÍCIL entender:
* "¿Por qué los datos en private son mejores que public?"
* Este Main DEMUESTRA la diferencia con ejemplos reales.
*
* ================================================
*/
public class Main {
public static void main(String[] args) {
// ================================================
// DEMOSTRACIÓN 1: CREAR UNA CUENTA
// ================================================
// ¿POR QUÉ?
// Primero, necesitamos una cuenta bancaria para demostrar.
// Creamos una cuenta con titular y saldo inicial.
//
// ¿CÓMO?
// new Cuenta(String titular, double saldo)
// - titular: "Juan García" (el dueño)
// - saldo: 1000.0 (dinero inicial)
//
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 1: CREAR UNA CUENTA");
System.out.println("=".repeat(60));
Cuenta cuenta1 = new Cuenta("Juan García", 1000.0);
System.out.println("✅ Cuenta creada");
System.out.println(" " + cuenta1.getResumen());
// ================================================
// DEMOSTRACIÓN 2: USAR GETTERS (LECTURA SEGURA)
// ================================================
// ¿POR QUÉ?
// Los getters SOLO LEEN datos, nunca los modifican.
// Son COMPLETAMENTE SEGUROS.
//
// ¿PARA QUÉ?
// - getTitular() → saber quién es el dueño
// - getSaldo() → saber cuánto dinero tiene
//
// ¿CÓMO FUNCIONA?
// Los getters devuelven el valor del atributo private.
// No pueden cambiar nada, solo leer.
//
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 2: USAR GETTERS (LECTURA SEGURA)");
System.out.println("=".repeat(60));
System.out.println("\nLeer datos (SEGURO con getters):");
System.out.println(" Titular: " + cuenta1.getTitular());
System.out.println(" Saldo: " + cuenta1.getSaldo() + "€");
System.out.println("✅ Los getters SON SEGUROS - solo LEEN, no modifican");
// ================================================
// DEMOSTRACIÓN 3: NO PUEDO ACCEDER DIRECTAMENTE
// ================================================
// ¿POR QUÉ?
// Los atributos son PRIVATE.
// Si intentas: cuenta1.saldo = -500
// El compilador grita: ❌ "saldo has private access in Cuenta"
//
// ¿PARA QUÉ?
// Para BLOQUEAR acceso directo a datos sensibles.
// Nadie puede hacer operaciones ilegales como saldo negativo.
//
// ¿CÓMO LO SABEMOS?
// Si descomtentas la siguiente línea, el código NO COMPILA:
//
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 3: ENCAPSULACIÓN (ATRIBUTOS PRIVADOS)");
System.out.println("=".repeat(60));
System.out.println("\n❌ ESTO NO FUNCIONARÍA (está comentado propósito):");
System.out.println(" // cuenta1.saldo = -500; ← ❌ ERROR: saldo is private");
System.out.println(" // cuenta1.saldo = 999999; ← ❌ ERROR: saldo is private");
System.out.println(" // cuenta1.titular = null; ← ❌ ERROR: titular is private");
System.out.println("\n✅ Por eso DEBEMOS usar métodos:");
System.out.println(" cuenta1.sacarDinero(100) ← ✅ PERMITIDO");
System.out.println(" cuenta1.ingresarDinero(50) ← ✅ PERMITIDO");
// ================================================
// DEMOSTRACIÓN 4: SACAR DINERO (CANTIDAD VÁLIDA)
// ================================================
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 4: SACAR DINERO (CANTIDAD VÁLIDA)");
System.out.println("=".repeat(60));
System.out.println("\nIntento 1: Sacar 100€ (es válido - tengo 1000€)");
cuenta1.sacarDinero(100);
System.out.println("Saldo después: " + cuenta1.getSaldo() + "€");
// ================================================
// DEMOSTRACIÓN 5: SACAR DINERO NEGATIVO (RECHAZADO)
// ================================================
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 5: SACAR CANTIDAD NEGATIVA (BLOQUEADO)");
System.out.println("=".repeat(60));
System.out.println("\nIntento 2: Sacar -500€ (INTENTO FRAUDULENTO)");
cuenta1.sacarDinero(-500);
System.out.println("Saldo después: " + cuenta1.getSaldo() + "€");
System.out.println("✅ El saldo NO cambió - el fraude fue BLOQUEADO");
// ================================================
// DEMOSTRACIÓN 6: SACAR MÁS DE LO QUE TENGO
// ================================================
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 6: SACAR MÁS DE LO QUE TENGO (BLOQUEADO)");
System.out.println("=".repeat(60));
System.out.println("\nIntento 3: Sacar 10000€ (tengo solo 900€)");
cuenta1.sacarDinero(10000);
System.out.println("Saldo después: " + cuenta1.getSaldo() + "€");
System.out.println("✅ El saldo NO cambió - el banco rechazó el retiro");
// ================================================
// DEMOSTRACIÓN 7: INGRESAR DINERO
// ================================================
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 7: INGRESAR DINERO");
System.out.println("=".repeat(60));
System.out.println("\nIngreso: Meter 500€");
cuenta1.ingresarDinero(500);
System.out.println("Saldo después: " + cuenta1.getSaldo() + "€");
// ================================================
// DEMOSTRACIÓN 8: INGRESAR DINERO NEGATIVO (RECHAZADO)
// ================================================
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 8: INGRESAR CANTIDAD NEGATIVA (BLOQUEADO)");
System.out.println("=".repeat(60));
System.out.println("\nIntento 4: Ingresar -1000€ (INTENTO FRAUDULENTO)");
cuenta1.ingresarDinero(-1000);
System.out.println("Saldo después: " + cuenta1.getSaldo() + "€");
System.out.println("✅ El saldo NO cambió - el fraude fue BLOQUEADO");
// ================================================
// DEMOSTRACIÓN 9: COMPARACIÓN - ¿POR QUÉ NO SETTER?
// ================================================
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 9: ¿POR QUÉ NO SETTER?");
System.out.println("=".repeat(60));
System.out.println("\nComparación - ¿SETTER vs MÉTODO CONTROLADO?");
System.out.println("\n❌ CON SETTER (PELIGROSO - sin validar):");
System.out.println(" public void setSaldo(double nuevoSaldo) {");
System.out.println(" this.saldo = nuevoSaldo; // Sin validación");
System.out.println(" }");
System.out.println("\n cuenta.setSaldo(-500); // ❌ ¡SALDO NEGATIVO!");
System.out.println(" cuenta.setSaldo(99999999); // ❌ ¡DINERO INFINITO!");
System.out.println(" cuenta.setSaldo(0.0001); // ❌ ¡DINERO PERDIDO!");
System.out.println("\n✅ CON MÉTODO CONTROLADO (SEGURO - con validación):");
System.out.println(" public void sacarDinero(double cantidad) {");
System.out.println(" if (cantidad <= 0) return; // Validar");
System.out.println(" if (cantidad > saldo) return; // Validar");
System.out.println(" saldo = saldo - cantidad; // Hacer");
System.out.println(" }");
System.out.println("\n cuenta.sacarDinero(-500); // ❌ BLOQUEADO");
System.out.println(" cuenta.sacarDinero(99999999); // ❌ BLOQUEADO");
System.out.println(" cuenta.sacarDinero(100); // ✅ PERMITIDO");
// ================================================
// DEMOSTRACIÓN 10: RESUMEN FINAL
// ================================================
System.out.println("\n" + "=".repeat(60));
System.out.println("DEMOSTRACIÓN 10: RESUMEN FINAL");
System.out.println("=".repeat(60));
System.out.println("\n📊 ESTADO FINAL DE LA CUENTA:");
System.out.println(" " + cuenta1.getResumen());
System.out.println("\n🔒 LECCIONES APRENDIDAS:");
System.out.println(" 1. Encapsulación = Proteger datos (private)");
System.out.println(" 2. Getters = Lectura SEGURA (sin modificar)");
System.out.println(" 3. Setters = Modificación PELIGROSA (sin validar)");
System.out.println(" 4. Métodos Controlados = Modificación SEGURA (con validación)");
System.out.println(" 5. Validación = Prevenir errores e insolvencia");
System.out.println("\n✅ Encapsulación en acción:");
System.out.println(" - ❌ No puedo hacer: cuenta.saldo = -500");
System.out.println(" - ✅ Debo hacer: cuenta.sacarDinero(100)");
System.out.println(" - ✅ El método VALIDA y CONTROLA el cambio");
System.out.println(" - ✅ Los datos están PROTEGIDOS y CONSISTENTES");
System.out.println("\n" + "=".repeat(60) + "\n");
}
}