简体   繁体   中英

Java code - how to set object variable

I am just learning and would like to know about a piece of code that sets the object variable.

What is the correct way to set object variable bfield in the follwoing test class?

public class test {
private String afield;

private String bfield;

public test() {

buildList();

}

public void buildList() {

    some code to derive and populate afield.

    this.bfield = this.afield;   //  ( 1)

    setBfield(afield);  // (2) say getter and setters do exist

    bfield = afield;  //  (3)
}

What is the right way to do? I soption 1 OK or option 2?

setter/getters are more preferable because you can encapsulate some processing in those accessor methods too


Also See

Any of the three will work, of course.

I generally don't like option 1, unless i'm differentiating between an instance member and an argument. For example, public void buildList(String bfield) { this.bfield = bfield; } public void buildList(String bfield) { this.bfield = bfield; } . this.everything is extra noise; if you don't need it, all it does is give the bugs more code to hide in. :)

Option 2 is more future-proof; if ever you change things so that something else has to be set along with bfield (or if bfield doesn't need a backing field at all -- for instance, if setting it should set something on a sub-object), you'll be glad you called setBfield -- cause you won't have a dozen places to change code that sets bfield . Basically, if you need and already have a setBfield method, i'd recommend using it in most cases.

If you have a field you know will always be contained within the object itself, and is independent of other fields, option 3 is typically faster. Plus, you don't have to create a setter (read: pollute your interface), if you don't want outside code to be able to set bfield as well.

Use eclipse! Let it do some work for you. Create a class Test like this.

public class Test {
   private String afield;
   private String bfield;
}

and then do these:

  • right click -> select 'Source' -> Generate constructor
  • right click -> select 'Source' -> Generate constructor with fields
  • right click -> select 'Source' -> Generate getters / setters

done :) and do lookup for java bean convention. your code would freak out any java exp dev! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM