Additional variables

Although it is allowed, before adding variables or fields to a data class, ask yourself, Are the fields derived from the state? Fields that are not derived from the state pose a serious violation of the initial concept of the data classes. The following code is an example that defines an additional field, style, derived from the state of the Emp data class: 

record Emp(String name, int age) { 
    private String style; 
    Emp(String name, int age) { 
        //.. initialize name and age 
        if (age => 15 && age =< 30) style = "COOL"; 
        else if (age >= 31 && age <= 50) style = "SAFE"; 
        else if (age >= 51) style = "ELEGANT"; 
    } 
    public String getStyle() { 
        return style; 
    } 
}

The preceding code works well because the state of the Emp data class is still derived from its state (the name and age fields). The getStyle method doesn't interfere with the state of Emp; it is purely an implementation detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.40