0

In Java, I understand why we define the instance field as private in some class, that is for protecting the encapsulation of a class. However, I am confused about the instance of that class. See below:

public class DotaHero {

private String name;

...

}

Till now, any outer class could not use the name directly! Then,

DotaHero zeus = new DotaHero();
zeus.name = "Zeus";

That is legal in Java. However, anyone who hate me would change my code easily, like:

zeus.name = "Chick";

Then, when I use object zeus to invoke the "zeusWrath" skill, it will show a script on screen, "The Chick is Furious!".........

Maybe someone would argue I was supposed to use setter method to define the name, and configure some checking mechanisms inside. However, my opponent still could directly access the name by zeus object.

I am sure I am misunderstanding something, but I can't find it...

Oliver
  • 147
  • 9
  • 4
    You cannot do `zeus.name = "Chick";` because field `name` is private. Can you please clarify your question? – Jaroslaw Pawlak Sep 14 '17 at 14:02
  • 4
    Try doing the `zeus.name = "Zeus"` assignment from another class, and see what happens. – Sergey Kalinichenko Sep 14 '17 at 14:02
  • 1
    OK, I found the problem. I put the main method in the class, so it could directly use the private fields. However, other class or object can't! Thanks a lot! How stupid I am :)))) – Oliver Sep 14 '17 at 14:09

0 Answers0