File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes OO, Patterns, UML and Refactoring and the fly likes Getter and Setter Methods!! Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Reply Bookmark "Getter and Setter Methods!!" Watch "Getter and Setter Methods!!" New topic
Author

Getter and Setter Methods!!

Brian Smith
Ranch Hand

Joined: Oct 26, 2002
Posts: 232
hi all,
could anyone please explain in simple way why the Getter and Setter methods are designed to get an access to attributes instead of making those attributes public and accessing them directly?
I would appreciate if you also could forward me a link that talks about concepts like this.
thanks.
Richard Jensen
Ranch Hand

Joined: May 14, 2003
Posts: 67
Originally posted by Namaste Sathi:
hi all,
could anyone please explain in simple way why the Getter and Setter methods are designed to get an access to attributes instead of making those attributes public and accessing them directly?
I would appreciate if you also could forward me a link that talks about concepts like this.
thanks.

The short answer is encapsulation -- a core concept of Object Oriented programming. If only methods can access your private data, then you can do a variety of things:
  • Change underlying data structure
  • Delegate the access to another object
  • Instrument the access or perform other checks
  • etc.


  • Oh, and having accessor methods allows you to synchronize reads and writes to the data so you can prevent race conditions.
    [ June 07, 2003: Message edited by: Richard Jensen ]

    Richard.<br />N 37 33 W 122 18
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    I have created a new FAQ entry for this topic: http://dirkschreckmann.dyndns.org:4000/JavaRanchFriki/view?AccessorMethods
    Please discuss!


    The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
    Don Kiddick
    Ranch Hand

    Joined: Dec 12, 2002
    Posts: 580
    That's great Ilja !
    Another point is that accssors (as opposed to direct variable access) seperate implementation from interface. All clients should care about is that an object can provide a value not that it is internally implemented as an instance variable, a database call or whatever.
    D.
     
     
    subject: Getter and Setter Methods!!
     
    developer file tools