Why shouldn’t I be using public variables in my Java class? [duplicate]

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.

2

It breaks encapsulation – the core principle here is that the fields of your class are implementation details, by exposing it as a public field, you are telling everything outside that class that it is an actual piece of data that is stored by the class – something external classes don’t need to know, they just need to be able to get or set that piece of data. As soon as you make something public, external classes should be able to depend on it, and it should not change often, by implementing as a method, you are retaining the flexibility to change the implementation at a later point without affecting users of the class.

If you wanted to change one of the fields so it’s calculated, or retrieved from a service when its called, you wouldn’t be able to without breaking other parts of your application. Other reasons are that it allows you to control access to the variable (i.e. make it immutable as you already highlighted). In setters you can also add checking code, and you can add behaviors to getters and setters that do other things when a variable is get or set (though this may not always be a good thing). You can also override a method in a derived class, you can’t override a field.

There are some very rare situations where it is better to have public field instead of a method – but this really only applies in very high performance applications (3D games & financial trading applications), unless you are writing one of these, avoid public fields – and if you do care about performance to that level, Java is probably not the best choice anyway.

Just a note on mutability – in general you should try to make things immutable until you have a genuine reason to make them mutable – the less your code exposes in its public API, the easier it is for long term maintenance, and in a multi-threaded situation, immutable objects are threadsafe, mutable objects need to implement locking.

9

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
Benefits of Encapsulation:

The fields of a class can be made read-only or write-only.

A class can have total control over what is stored in its fields.

The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.he public methods are the access points to this class’s fields from the outside java world. Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật