Why shouldn't I be using public variables in my Java class?

Posted by Omega on Programmers See other posts from Programmers or by Omega
Published on 2012-11-23T01:03:20Z Indexed on 2012/11/23 5:09 UTC
Read the original article Hit count: 160

Filed under:
|

In school, I've been told many times to stop using public for my variables. I haven't asked why yet.

This question: Are Java's public fields just a tragic historical design flaw at this point? seems kinda related to this. However, they don't seem to discuss why is it "wrong", but instead focus on how can they use them instead.

Look at this (unfinished) class:

public class Reporte {

    public String rutaOriginal;
    public String rutaNueva;
    public int bytesOriginales;
    public int bytesFinales;
    public float ganancia;

    /**
     * Constructor para objetos de la clase Reporte
     */
    public Reporte() {

    }
}

No need to understand Spanish. All this class does is hold some statistics (those public fields) and then do some operations with them (later).

I will also need to be modifying those variables often. But well, since I've been told not to use public, this is what I ended up doing:

public class Reporte {

    private String rutaOriginal;
    private String rutaNueva;
    private int bytesOriginales;
    private int bytesFinales;
    private float ganancia;

    /**
     * Constructor para objetos de la clase Reporte
     */
    public Reporte() {

    }

    public String getRutaOriginal() {
        return rutaOriginal;
    }

    public String getRutaNueva() {
        return rutaNueva;
    }

    public int getBytesOriginales() {
        return bytesOriginales;
    }

    public int getBytesFinales() {
        return bytesFinales;
    }

    public float getGanancia() {
        return ganancia;
    }

    public void setRutaOriginal(String rutaOriginal) {
        this.rutaOriginal = rutaOriginal;
    }

    public void setRutaNueva(String rutaNueva) {
        this.rutaNueva = rutaNueva;
    }

    public void setBytesOriginales(int bytesOriginales) {
        this.bytesOriginales = bytesOriginales;
    }

    public void setBytesFinales(int bytesFinales) {
        this.bytesFinales = bytesFinales;
    }

    public void setGanancia(float ganancia) {
        this.ganancia = ganancia;
    }
}

Looks kinda pretty. But seems like a waste of time.

Google searches about "When to use public in Java" and "Why shouldn't I use public in Java" seem to discuss about a concept of mutability, although I'm not really sure how to interpret such discussions. I do want my class to be mutable - all the time.

© Programmers or respective owner

Related posts about java

Related posts about best-pactice