
January 2nd, 2013, 01:42 AM
|
 |
Daniel Schildsky
|
|
Join Date: Mar 2004
Location: KL, Malaysia.
|
|
|
Manipulating data of an instance of class variable
Accessing and manipulating data of a class member within a class using direct reference is a bad practice and it completely beats the purpose of encapsulation in object-oriented software design.
Getter/setter methods can be declared for the purpose of data access by a 3rd party class, where all members in the Dog class should be declared private or protected. The data/class members in the Dog class that are supposed to be accessible by other classes should have their respective getter/setter methods declared in the class itself, and all other classes should only allowed to access/change the values of these data/members via these getter/setter methods.
java Code:
Original
- java Code |
|
|
|
public class Foo{ Dog dogReference; public Foo(Dog _dog){ dogReference = _dog; } public bar(){ dogReference.setName("Fido"); } public void makeDogBark(){ System. out. println(dogReference. getName()); } public static void main (String args []){ Foo foo = new Foo(new Dog()); System. out. println("name of the dog before bar()"); foo.makeDogBark(); foo.bar(); System. out. println("name of the dog after bar()"); foo.makeDogBark(); } } public class Dog { /** * Constructor. **/ public Dog(){ name = "Dido"; //default name. } /** * Setter for name. **/ public void setName (String _name ){ name = _name; } /** * Getter for name. **/ return name; } }
__________________
When the programming world turns decent, the real world will turn upside down.
Last edited by tvc3mye : January 2nd, 2013 at 02:01 AM.
Reason: missed out some words and added sample codes
|