Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Use of Getters?

what does getter function do exactly? we set public string getValue() { return mValue; }

Why we do so and what's the logic behind it?

2 Answers

I learn best by simple, whimsical analogies. If you're like me, this should help:

Compare the activity of programming to assembling the perfect machine. A machine that no matter how much load you put through it, will process, package, and ship the load to where ever it need to be.

Think of Amazon webstore. Millions of orders are being processed a day, each requiring its individual set of unique order information. Quite the load; quite the machine.

Organized information is called data. Data can be represented by binary. Binary can be communicated via electrical signals. What I'm telling you applies to all levels of computer science.

The getters and setters facilitate a concept called encapsulation. Instead of writing:

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

it's better to write:

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

Encapsulation provides better control, it allows for better scalability, and it arguably allows for better readability. Use of encapsulation is considered best practice.

This specific code snipet of getters allows you better control of the update of the field. For example, you could:

  • 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.

in this case

public String mValue;

the other classes can change and read mValue

in this case

private String mValue;
public String getValue() {
  return mValue; 
}

the other classes can only read mValue and only the class that contains the mValue member can change it. with getter methods you can protect the data of the class from the outside