How public members of a class causes havoc in java? -


how public members of class causes havoc in java? can please explain example? tried create such situation couldn't succeed. found them equivalent 'protected' access modifier.

it allows invalid values, breaking encapsulation.

public class clock {     public int hours;     public int minutes; } 

then, in unrelated code...

clock clock = new clock(); clock.hours = 42; clock.minutes = 99; 

having them private setter , getter methods allows encapsulation enforce proper values.

public class clock {     private int hours;     private int minutes;     public void sethours(int hours) {         if (hours < 0 || hours > 23) throw new illegalargumentexception("bad range");         this.hours = hours;     }     // likewise "setminutes" method. } 

here's tutorial page on encapsulation in java on encapsulation's benefits. quoting:

  • the fields of class can made read-only or write-only.

  • a class can have total control on stored in fields.

  • the users of class not know how class stores data. class can change data type of field, , users of class not need change of code.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -