I have a problem with understanding the interface Comparable
.
The application by console consists of printing the respective objects and comparing which is the most expensive and cheapest product.
The problem is that I do not understand how to apply it to my application so that it prints by the method toString()
:
- Most expensive product:
- Cheapest product:
This is the functional code of the application:
Product:
package ar.com.minisuper.sistema;
public abstract class Producto implements Comparable<Producto> {
protected String nombre;
protected int precio;
public Producto(String nombre, int precio) {
this.nombre = nombre;
this.precio = precio;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public double getPrecio() {
return precio;
}
public void setPrecio(int precio) {
this.precio = precio;
}
@Override
public int compareTo(Producto o) {
return this.getPrecio()>o.getPrecio()?1:this.getPrecio()<o.getPrecio()?-1:0;
}
}
Drink:
package ar.com.minisuper.sistema;
public class Bebida extends Producto {
private double unidadVenta;
public Bebida(String nombre, double unidadVenta, int precio) {
super(nombre, precio);
this.unidadVenta = unidadVenta;
}
@Override
public String toString() {
return "Nombre: " + this.nombre + " /// " + "Litros: " + this.unidadVenta + " /// " + "Precio: $" + this.precio;
}
}
Shampoo:
package ar.com.minisuper.sistema;
public class Shampoo extends Producto {
private int unidadVenta;
public Shampoo( String nombre, int unidadVenta, int precio ) {
super(nombre, precio);
this.unidadVenta = unidadVenta;
}
@Override
public String toString() {
return "Nombre: " + this.nombre + " /// " + "Contenido: " + this.unidadVenta + "ml" + " /// " + "Precio: $" + this.precio;
}
}
Fruit:
package ar.com.minisuper.sistema;
public class Fruta extends Producto {
private String unidadVenta;
public Fruta(String nombre, int precio, String unidadVenta) {
super(nombre, precio);
this.unidadVenta = unidadVenta;
}
@Override
public String toString() {
return "Nombre: " + this.nombre + " /// " + "Precio: $" + this.precio + " /// " + "Unidad de venta: " + this.unidadVenta;
}
}
And the main:
package ar.com.minisuper.sistema;
public class Main {
public static void main(String[] args) {
Bebida colaZero = new Bebida( "Coca-Cola Zero", 1.5, 20 );
Bebida cola = new Bebida( "Coca-Cola", 1.5, 18 );
Shampoo shampoo = new Shampoo ( "Shampoo Sedal", 500, 19 );
Fruta frutilla = new Fruta( "Frutillas ", 64, "kilo" );
System.out.println(colaZero);
System.out.println(cola);
System.out.println(shampoo);
System.out.println(frutilla);
}
}