forked from mouredev/hello-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProduct.java
More file actions
48 lines (38 loc) · 1.33 KB
/
Copy pathProduct.java
File metadata and controls
48 lines (38 loc) · 1.33 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
package basic.c08_oop;
public class Product {
private String name;
private double price;
// Constructor
public Product(String name, double price) {
this.name = name;
setPrice(price); // valida el precio al crear el objeto
}
// Getter
public double getPrice() {
return price;
}
public String getName() {
return name;
}
// Setter con validación
public void setPrice(double price) {
if (price > 0) {
this.price = price;
} else {
System.out.println("Precio no válido. Debe ser mayor que 0.");
}
}
// Método para aplicar descuento
public void applyDiscount(double percentage) {
if (percentage > 0 && percentage <= 100) {
setPrice(price - (price * percentage / 100)); // usa setter para validar
System.out.println("Se aplicó un descuento del " + percentage + "%, nuevo precio: " + price);
} else {
System.out.println("Descuento no válido");
}
}
// Método opcional: mostrar info del producto
public void showInfo() {
System.out.println("Producto: " + name + ", Precio: " + price);
}
}