Search code examples
javaoopencapsulationsettergetter

Can you help me understand encapsulation please (Beginner)?


I've been using a Java book which has been excellent so far but it hasn't been to good at explaining the reason why we use setters and getter. I've searched other posts but none have really helped me specifically. I'll just post a program from the book and explain my problems with it.

   package lesson1;
public class GoodDog {
   private int size;

   public void setSize(int sz){
      if(sz > 10){
         size = sz;
      }
   }
   public int getSize(){
     return size;
   }
}

Second class:

   package lesson1;
public class GoodDogTestDrive {

   public static void main(String[] args) {
      GoodDog one = new GoodDog();
      one.setSize(15);
      System.out.println(one.getSize());
   }
}

This is my first post so if it doesn't come out as code then forgive me. Don't ask why the classes are named that, I had no imagination and just used the book's name.

Anyway, my understanding is that encapsulation (To me this basically means getters and setters) prevents the direct access to instant variables. The only valid reason for this is because some values of instant variables should not be allowed.

For example say we had int height; (Instant variable) We should not be able to say object.height = 0; ('object' being a random reference variable). In my little program it is simply a dog's height with a simply restriction. It's not meant to make sense but I'm just trying to make sense of this concept. Is encapsulation simply meant for programming firms when programmers need to use each others code to. say, make a game for example or is it different?

I watched a video also stating that it simply makes code easier to manage. However I still don't feel that I fully understand this concept. Can someone please explain this to me in simple terms. Please note that I'm a beginner and will not understand examples involving intermediate code.

Thank you for your help.


Solution

  • If I understand what you're asking, you can think of encapsulation as the practice of utilizing data-hiding features of a programming language. One of the core principles of object orientation is that objects contain both data and methods to operate on that data. Encapsulation is the general internalization of the data so that only an object's own methods can modify the object's state.