Constructor with POO constants. Java

0

I have a question about a little code I've seen. In an exercise, creating an Appliances class, you are asked to create a series of attributes (price, color, consumption, weight) and that by default, the color will be white, the energy consumption will be F, the Base price is € 100 and the weight of 5 kg (using constants).

//Constantes
protected final static String COLOR_DEF="blanco";
protected final static char CONSUMO_ENERGETICO_DEF='F';
protected final static double PRECIO_BASE_DEF=100;
protected final static double PESO_DEF=5; 

So when I saw the solution I saw this:

//Constructor por defecto
public Electrodomestico(){
    this(PRECIO_BASE_DEF, PESO_DEF, CONSUMO_ENERGETICO_DEF, COLOR_DEF);
}

The question is that I do not understand what this last constructor does, besides when I copy it in Eclipse it gives me an error because it tells me that the constructor is not defined ..

    
asked by Javi 13.01.2018 в 20:05
source

1 answer

1

This last constructor is invoking another constructor (since this is done by means of this(); , and when entering the parameters you would be indicating that you assign those values to the corresponding attributes.

When you see the code that you show us, we can deduce two things:

The first is that you have a class called Electrodomestico which has (in addition to the four static variables) 4 variables to define color, energy consumption, base price and weight. Something like this:

// Atributos de la clase
private String color;
private char consumo_energetico;
private double precio_base;
private double peso;

The second thing that can be deduced is that you have (or must have) a second constructor with the class parameters for each variable of the class (shown above). Finally, your class should look something like this:

public class Electrodomestico {

    //Constantes
    protected final static String COLOR_DEF="blanco";
    protected final static char CONSUMO_ENERGETICO_DEF='F';
    protected final static double PRECIO_BASE_DEF=100;
    protected final static double PESO_DEF=5; 

    // Atributos de la clase
    private String color;
    private char consumo_energetico;
    private double precio_base;
    private double peso;

    //Constructor por defecto
    public Electrodomestico() {
        this(PRECIO_BASE_DEF, PESO_DEF, CONSUMO_ENERGETICO_DEF, COLOR_DEF);
    }

    public Electrodomestico(String color, char consumo_energetico, double precio_base, double peso) {
        this.color = color;
        this.consumo_energetico = consumo_energetico;
        this.precio_base = precio_base;
        this.peso = peso;
    }

    // Aquí va más código, GETTERS y SETTERS... 
}

In this way, when using this(PRECIO_BASE_DEF, PESO_DEF, CONSUMO_ENERGETICO_DEF, COLOR_DEF); you would be calling the second constructor and assigning the default values, giving us as a result a new household appliance with the default characteristics.

    
answered by 13.01.2018 / 20:27
source