开发者

What does getters & setters method do in Java, how are they different from normal methods, and why is the getMethod sometime missing? [duplicate]

This question already has answers here: Closed 11 years ago.

I am new to Java.

  1. Can any one explain what the getters and setters method do?

  2. where we must use getters setters method and how it differ from the normal method?

  3. And i saw some coding having only setter method so here why getters method not declared?

    开发者_开发技巧
    private String wheel;
    
    /**
     * @param wheel the wheel to set
     */
    public void setWheel(String wheel) {
        this.wheel = wheel;
    }
    public void rotate() {
        System.out.println(wheel+"rotated");
    }
    


Can any one explain what the getters and setters method do?

Get-methods and set-methods help in encapsulating data. That's all. Instead of writing

object.wheel = new Wheel(5);
// ...
object.wheel.rotate();

you do

object.setWheel(new Wheel(5));
// ...
object.getWheel().rotate();

This gives you better control of the update of the field. You could for instance:

  • Throw an IllegalArgumentException if the wheel doesn't fit.
  • Compute or load a new wheel on the fly in the getWheel-method.
  • Let other object listen for wheel-updates

etc.

where we must use getters setters method and how it differ from the normal method?

You don't have to use getters and setters, it's just good practice.

Technically speaking getters and setters are no different from normal methods. They just have a specific (simple) purpose.

And i saw some coding having only setter method so here why getters method not declared?

The author of the class simply didn't want to expose the wheel-object to the user. The reasons for this may vary.


Getters expose the fields. So you saw code with only setters- that makes it write only, with no read privileges. Setter => Write, Getter => Read.

These methods are typically very simple, and you can choose to handle errors in them too.

Normally you would have a private field, and either a getter or a setter (or both) to access it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜