What are the alternatives to public fields?

前端 未结 12 2666
刺人心
刺人心 2021-02-19 15:05

I am programming a game in java, and as the question title suggestions i am using public fields in my classes. (for the time being)

From what i have seen public fields a

12条回答
  •  礼貌的吻别
    2021-02-19 15:37

    In Java, using private fields with getters/setters is the recommend practice, provided external clients of your class really need access to those fields.

    Otherwise keep them as private fields and simply don't provide a getter/setter.

    There are various reasons why this is a best practice:

    1. If clients are using your field directly and later something needs to change regarding that, you're stuck. With a getter you can do a whole lot of things before the field is accessed.
    2. There is something called the JavaBeans specification that requires you to use getter/setters. Without them your class (then called bean) won't interoperate with that. JSP and JSF's EL is one example of something that required your class to comply with JavaBeans standards.

    (p.s. unrelated to your question, but you'd better not declare backPack as an ArrayList. Declare as List; code to interface, not to implementation)

提交回复
热议问题